farshid83 farshid83 - 1 month ago 14
Android Question

Change Edittext focus and make an ImageView disappear

I'm working on an app which has two EditTexts and two ImageViews (my ImageView is a delete icon EditText)

I want that when I set the focus on EditText1, ImageView1 appears and ImageView2 disappears and when I set the focus on EditText2, ImageView2 appears and ImageView1 disappears.

I think I should use the

TextWatcher()
methods instead of
setOnKeyListener()
, but I don't know how to.

I wrote this code in the
onCreate()
method, but I have one problem: when I set the focus on EditText1, I have to write something in it to make image_1 appear and image_2 disappear (and vice-versa when I set the focus on EditText2)

editText1.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
image_1.setVisibility(View.VISIBLE);
image_2.setVisibility(View.INVISIBLE);

return false;
}
});
editText2.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
image_1.setVisibility(View.INVISIBLE);
image_2.setVisibility(View.VISIBLE);
return false;
}
});

Answer

I don't think OnKeyListener or TextWatcher would be the correct solution to your demand.

What you want here instead is OnFocusChangeListener:

    View.OnFocusChangeListener focusChangeListener1 = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            image_1.setVisibility(View.VISIBLE);
            image_2.setVisibility(View.INVISIBLE);   
        }
    }
    editText1.setOnFocusChangeListener(focusChangeListener1);

    View.OnFocusChangeListener focusChangeListener2 = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            image_1.setVisibility(View.INVISIBLE);
            image_2.setVisibility(View.VISIBLE);
        }
    }
    editText2.setOnFocusChangeListener(focusChangeListener2);