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??
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??
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.
set this in your xml
android:focusable="true"
android:focusableInTouchMode="true"
and you can set this on onViewCreated program editText.isFocusableInTouchMode();
editText.setFocusable(true);
Add these lines from class,
EditText.isFocusableInTouchMode();
EditText.setFocusable(true);
EditText.requestFocus();
or add these attributes in layout,
android:focusable="true"
android:focusableInTouchMode="true"
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.