【问题标题】:keyListener does not recognise inputkeyListener 无法识别输入
【发布时间】:2020-06-04 15:35:58
【问题描述】:

我在 editText 上有一个 KeyListener,如下所示:

tip = (EditText) findViewById(R.id.tip);
tip.setOnKeyListener(new EditText.OnKeyListener(){
    public boolean onKey(View v, int keyCode, KeyEvent event) {

        Log.i("debug123", "onKeyListener. event.getKeyCode(): " + event.getKeyCode());

        // If the event is a key-down event on the "enter" button
        if ((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            checkInput();
            return true;
        }
        return false;
    }
});

但是没有识别出软键盘笔划。? 只有当我使用 BACK 按钮(HardwareButton)离开 Activity 时,Listener 才会识别该操作。 但从我阅读的所有内容来看,如果我想在 EditText 上使用用户输入,这就是要走的路。

【问题讨论】:

  • 使用setOnEditorActionListener 代替setOnKeyListener 来达到您的目的
  • 检查this post是否对你有任何帮助。

标签: android android-edittext android-softkeyboard onkeylistener


【解决方案1】:

setOnKeyListener

注册一个回调,以便在按下 硬件 键时调用 这种观点。 软件输入法中的按键一般不会 触发此监听器的方法。

setOnEditorActionListener

设置一个特殊的监听器,当一个动作被执行时被调用 文本视图。这将在按下 enter 键 时调用,或者当 提供给 IME 的动作由用户选择。

要使用setOnEditorActionListener 解决您的问题,请查看以下内容:

  • imeOptionsinputType 添加到您的EditText
<EditText
    android:id="@+id/tip"
    android:imeOptions="actionDone"
    android:inputType="text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
  • 然后将setOnEditorActionListener添加到EditText
tip.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        if ( (actionId == EditorInfo.IME_ACTION_DONE) || (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) ) {
            checkInput();
            return true;
        } else {
            return false;
        }
    }
});

这里,

  • actionId == EditorInfo.IME_ACTION_DONE 处理来自软键盘 (IME) 的操作
  • event.getKeyCode() == KeyEvent.KEYCODE_ENTER &amp;&amp; event.getAction() == KeyEvent.ACTION_DOWN 从硬件键盘处理回车键

【讨论】:

  • 不,这对我不起作用。我在较旧的智能手机上尝试了该应用程序(使用 setOnKeyListener-Solution),它按预期工作。但不是在我的新手机上。
  • 您能更新您的代码吗?您尝试过哪些布局?这应该有效。经过测试
  • upps,我做了没有输入部分的布局部分。现在可以了,谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 2021-05-07
  • 2014-10-05
  • 2013-05-28
  • 1970-01-01
相关资源
最近更新 更多