【问题标题】:programically click EditText以编程方式单击 EditText
【发布时间】:2021-09-30 15:34:41
【问题描述】:

我想在按下按钮后以编程方式单击 editText。 选择单选按钮“pitot_area”时,我希望edittext与此选择相关联的编辑部以编程方式点击,因此用户在屏幕上没有“单击”,它会自动发生。

到目前为止我已经尝试过

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) 问题,但无法为我的代码实现它。

【问题讨论】:

标签: android kotlin keyboard click focus


【解决方案1】:

要将焦点直接设置到 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)
}

【讨论】:

  • 您好,感谢您的回答,我刚刚尝试过,并收到错误 Type mismatch: inferred type is String but Context is expected with INPUT_METHOD_SERVICE 在读取中下划线
  • 我已经为 Activity 和 Fragment 添加了代码
  • 我似乎无法让这种方法起作用,有什么建议吗?
  • 您是否尝试过使用我添加的代码?它在我的代码中工作正常
  • 对于我看到的错误未解决的参考 llMainView 的片段代码,我想用什么来代替它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-16
  • 1970-01-01
  • 2013-10-09
  • 2011-10-22
  • 2015-03-17
  • 1970-01-01
  • 2014-01-08
相关资源
最近更新 更多