8

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??

hanjiman
  • 465
  • 1
  • 6
  • 17
  • Use Edittext edittext = view.findViewById(R.id.your_id); then if(!edittext.getfocus()) edittext.requestFocus()/ edittext.setFocus(true); – Ranjeet Chouhan Mar 13 '20 at 05:53

4 Answers4

13

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.

Naung9
  • 209
  • 1
  • 8
5

set this in your xml

android:focusable="true"
android:focusableInTouchMode="true"

and you can set this on onViewCreated program editText.isFocusableInTouchMode(); editText.setFocusable(true);

Amit pandey
  • 1,149
  • 1
  • 4
  • 15
1

Add these lines from class,

EditText.isFocusableInTouchMode();
EditText.setFocusable(true); 
EditText.requestFocus(); 

or add these attributes in layout,

android:focusable="true"
android:focusableInTouchMode="true"
Rashiq
  • 650
  • 1
  • 9
  • 23
0

Add this kotlin extension function

fun EditText.focus() {
    text?.let { setSelection(it.length) }
    postDelayed({
        requestFocus()
        val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
    }, 200)
}

and call it on your EditText in onViewCreated.

yaugenka
  • 2,602
  • 2
  • 22
  • 41