以编程方式单击 EditText

时间:2021-07-23 13:53:53

标签: android kotlin keyboard click focus

我想在按下按钮后以编程方式单击 editText。 When a radio button "pitot_area" is selected, I want the editText associated with this selection to be programmatically clicked, so the user has one less "click" on the screen and it happens automatically.

到目前为止我已经尝试过

performClick()
callOnClick()
requestFocus()

我希望此代码所在的区域如下:

root.pitot_area.setOnClickListener {
setAreaLabels(root)         
evNodeItem.kvParams = false
evNodeItem.PitotRectArea = false
evNodeItem.PitotRoundArea = false
evNodeItem.areaParams = true

root.area_edit_text.requestFocus()
            

我尝试过的另一种方法是

root.area_edit_text.setFocusableInTouchMode(true);
                root.area_edit_text.setFocusable(true);
                root.area_edit_text.requestFocus();

对于上面的代码行,我在 .xml 文件中有 editText

android:focusable="false"
android:focusedByDefault="false"

错误未显示并且代码生成,似乎此代码不是在 kotlin 中读取的?有没有人对如何做到这一点有任何想法?谢谢!

编辑 我查看了 -> 以编程方式(Kotlin)焦点编辑文本(Kotlin)问题在下面建议,但无法为我的代码实现它。

1 个答案:

答案 0 :(得分:0)

要将焦点直接设置到 EditText,您必须在将焦点设置到 EditText 后打开键盘。

将此行写入您的按钮点击:

对于活动:

button.setOnClickListener {
    
    editText.isFocusableInTouchMode = true
    editText.requestFocus()
        
    val inputMethodManager: InputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.toggleSoftInputFromWindow(llMainView.applicationWindowToken, InputMethodManager.SHOW_FORCED, 0)
        
}

对于片段:

  button.setOnClickListener {
        
   editText.isFocusableInTouchMode = true
   editText.requestFocus()

   val inputMethodManager: InputMethodManager = activity!!.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
   inputMethodManager.toggleSoftInputFromWindow(llMainView.applicationWindowToken, InputMethodManager.SHOW_FORCED, 0)
}
相关问题