我有一个包含如下视图的布局:
<LinearLayout>
<TextView...>
<TextView...>
<ImageView ...>
<EditText...>
<Button...>
</linearLayout>
如何以编程方式在我的EditText上设置焦点(显示键盘)?
我已经尝试过了,它只在我正常启动我的活动时才起作用,但当我在TabHost中启动它时,它不起作用。
txtSearch.setFocusableInTouchMode(true);
txtSearch.setFocusable(true);
txtSearch.requestFocus();
我推荐使用一个LifecycleObserver,它是Android Jetpack中使用生命周期感知组件处理生命周期的一部分。
当片段/活动出现时,我想打开和关闭键盘。首先,为EditText定义两个扩展函数。你可以把它们放在项目的任何地方:
fun EditText.showKeyboard() {
requestFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
fun EditText.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(this.windowToken, 0)
}
然后定义一个LifecycleObserver,当Activity/Fragment到达onResume()或onPause时打开和关闭键盘:
class EditTextKeyboardLifecycleObserver(private val editText: WeakReference<EditText>) :
LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun openKeyboard() {
editText.get()?.postDelayed({ editText.get()?.showKeyboard() }, 100)
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun closeKeyboard() {
editText.get()?.hideKeyboard()
}
}
然后将下面的行添加到您的任何片段/活动中,您可以在任何时候重用LifecycleObserver。例如,对于片段:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// inflate the Fragment layout
lifecycle.addObserver(EditTextKeyboardLifecycleObserver(WeakReference(myEditText)))
// do other stuff and return the view
}
第一个方法:
etPassword.post(() -> {
etPassword.requestFocus();
InputMethodManager manager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
manager.showSoftInput(etPassword, InputMethodManager.SHOW_IMPLICIT);
});
第二种方式:
在清单:
<activity
android:name=".activities.LoginActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible"/>
在代码:
etPassword.requestFocus();