如何收听用户的按键输入?

时间:2019-01-09 18:47:16

标签: input kotlin keyboard enter submit-button

我设法获得一个Alert对话框,并弹出一个editText来处理来自用户的输入。当他们按键盘上的Enter键时,我将如何处理提交过程?我想避免使用按钮来提交和更改文本。希望我能提供足够的细节,因为我对此还很陌生。感谢您的宝贵时间。

Phone App Pic

警报对话框:

@Repository
public interface ClientRepository extends JpaRepository<Client, Long>, JpaSpecificationExecutor<Client> {
@Query( value = "select * from client where center_id in\n" +
    "(select  id  from    (select * from center  order by parent_center_id, id) center_sorted,  (select @pv=:centerId) initialisation\n" +
    "where   find_in_set(parent_center_id, @pv) and  length(@pv:=concat(@pv, ',', id))) or center_id=:centerId;" ,nativeQuery = true)

Page<Client> findAllByCenterId(@Param("centerId") Long centerId, Pageable pageable) ;

更新:

(1..912).forEach {
        val id = resources.getIdentifier("Price$it", "id", packageName)
        val tv = findViewById<TextView>(id)
        tv.setOnLongClickListener {

            //Alert Window
            val alertDialog = AlertDialog.Builder(this@MainActivity)
            alertDialog.setTitle("NEW PRICE")
            val input = EditText(this@MainActivity)
            val lp = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
            )
            input.layoutParams = lp
            alertDialog.setView(input).show()
            return@setOnLongClickListener true

        }
    }

2 个答案:

答案 0 :(得分:1)

您可以为OnKeyListener设置自定义EditText

val input = EditText(this@MainActivity)
input.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
    if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
        // your code here
        true
    }
    false
})

答案 1 :(得分:0)

您需要为OnEditorActionListener设置EditText

val input = EditText(this@MainActivity)
input.setOnEditorActionListener { _, actionId, event ->
    // If triggered by an enter key, this is the event; otherwise, this is null.
    // if shift key is down, then we want to insert the '\n' char in the TextView;
    if (event == null || event.isShiftPressed) return@setOnEditorActionListener false
    // TODO: your code goes here
    return@setOnEditorActionListener true
}

在此示例中,我另外检查是否未按下shift键。它可以在具有任何类型键盘的所有设备上使用。

注释1 。我们在这里不需要actionId,但是您仍然可以为键盘设置不同的操作(使用input.imeOptions = EditorInfo.IME_ACTION_SEND或xml属性android:imeOptions="actionSend"),并且将针对任何类型的操作调用侦听器键盘类型。 Read Android documentation以了解有关动作的更多信息。

注释2 。我为所有这些逻辑做了自定义包装,使我能够以最简单的方式设置Enter键侦听器。检出this gist

editText.setOnEnterActionListener {
    Toast.makeText(context, "Click", Toast.LENGTH_SHORT).show()
}