How to set focus to editText when fragment start?

邮差的信 提交于 2020-12-12 03:58:54

问题


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


回答1:


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.




回答2:


set this in your xml

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

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




回答3:


Add these lines from class,

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

or add these attributes in layout,

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


来源:https://stackoverflow.com/questions/60665435/how-to-set-focus-to-edittext-when-fragment-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!