androidandroid-edittextsetfocus

How to set focus to editText when fragment start?


When MyFgment appear in screen, I want to set cursor focus on EditText in MyFragment automatically. I've tried EditText.requestFocus(), but it doesn't focus on EditText. How can I do??


Solution

  • editText.requestFocus() will put focus to your View if it is focusable . But I guess you want to show keyboard when it is focused. If I am right then the following code might work for you.

    editText.requestFocus();
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    

    The code is from this post. You can also check Android Developers for details.