Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 301
hanjiman Avatar asked Mar 13 '20 05:03

hanjiman


People also ask

How do I know if EditText has focus?

You can use View. OnFocusChangeListener to detect if any view (edittext) gained or lost focus. This goes in your activity or fragment or wherever you have the EditTexts.

How do I change the default text in EditText?

You can use EditText. setText(...) to set the current text of an EditText field.


2 Answers

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.

like image 92
Naung9 Avatar answered Sep 19 '22 23:09

Naung9


set this in your xml

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

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

like image 39
Amit pandey Avatar answered Sep 18 '22 23:09

Amit pandey