片段启动时如何将焦点设置为editText?

han*_*man 5 android setfocus android-edittext

MyFgment出现在屏幕上,我想设置光标焦点上EditTextMyFragment自动。我试过了EditText.requestFocus(),但它不专注于EditText. 我能怎么做??

小智 8

View如果它是可聚焦的,则editText.requestFocus() 会将焦点放在您的身上。但是我猜您想在聚焦时显示键盘。如果我是对的,那么下面的代码可能对你有用。

editText.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
Run Code Online (Sandbox Code Playgroud)

代码来自这篇文章。您还可以查看Android Developers了解详细信息。


Ami*_*dey 5

在你的 xml 中设置它

android:focusable="true"
android:focusableInTouchMode="true"
Run Code Online (Sandbox Code Playgroud)

你可以在 onViewCreated 程序上设置它editText.isFocusableInTouchMode(); editText.setFocusable(true);