Search code examples
javaandroidandroid-edittextontouchlistener

Requesting focus to a EditText after another EditText has been touched?


I have 2 EditText (myEditText1 and myEditText2)
And I need when touch myEditText1
1. Do some business [No problem here and required business applied]
2. Then request focus to myEditText2 [ No luck? ]

final EditText myEditText1 = (EditText) findViewById(R.id.myEditText1);
final EditText myEditText2 = (EditText) findViewById(R.id.myEditText2);

// ...

myEditText1.setOnTouchListener(new View.OnTouchListener()
{
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        // My business when myEditText1 touched [ OK ]
        // ...

        // TODO
        // Need to request focus to another EditText myEditText2 ?

        return false;
    }
});

I try some solutions like following trials
But no luck and focusing still on myEditText1

myEditText2.requestFocus();

Related questions
EditText request focus
Change Focus to EditText Android


Solution

  • You can set an OnClickListener on your edit text like this:

    this.editText1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //your code
                    editText2.requestFocus();
                }
    });
    

    Just take care about a special case
    onClick() is not called when the EditText doesn't have focus
    And you can find details of this case in the following question thread
    onClick event is not triggering | Android