以编程方式聚焦编辑文本 (Kotlin) [英] Focus Edit Text Programmatically (Kotlin)
问题描述
我有一个 createEditText
函数,它创建一个 EditText
并将其添加到视图中.我的问题是,一旦将其添加到视图中,用户必须点击 EditText
才能调用键盘并进行编辑.我想要做的是让它在创建 EditText
后,用户会自动进入编辑模式.
I have a createEditText
function that creates an EditText
and adds it to the view. My issue is that once it is added to the view, the user has to tap the EditText
in order for the keyboard to be called and editing to work. What I am trying to do is to have it so that once the EditText
is created, the user is automatically taken to the edit mode.
在 IOS 编程中,有一个名为 becomeFirstResponder()
的函数可以实现这一点.android 等价物是什么?
In IOS programming, there is a function called becomeFirstResponder()
which achieves this. What would the android equivalent be?
我尝试过的事情:
myEditText.requestFocus()
myEditText.isActivated
myEditText.isFocused
myEditText.isSelected
myEditText.isEnabled
推荐答案
不幸的是,仅调用 EditText#requestFocus
是不够的.除此之外,您还必须调用InputMethodManager#showSoftInput
.以下实用方法应该有效:
Unfortunately it is not enough to call only EditText#requestFocus
. In addition to this you also have to call the InputMethodManager#showSoftInput
. Following utility method should work:
fun openSoftKeyboard(context: Context, view: View) {
view.requestFocus()
// open the soft keyboard
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
这篇关于以编程方式聚焦编辑文本 (Kotlin)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!