我正在创建一个Dialog
与 Dialog.OnKeyListener
拦截一些按键。
出于测试目的,我的onKey
方法总是返回 true
这意味着我的Dialog.OnKeyListener
正在消耗所有关键事件。
我有一个EditText
在我的Dialog
我发现如果我设置为 inputType
text
以外的其他类型(例如number
),EditText
没有收到任何关键事件,并且表现得像不可编辑(正如预期的那样,因为我的 Dialog.OnKeyListener
正在消耗所有事件),但是如果我设置 inputType
如inputType="text"
,EditText
接收所有关键事件(可编辑)。
对于我的示例,我有一个 Dialog
与 OnKeyListener
消耗所有事件和两个 EditText
s,其中一个 inputType="text"
通过 inputType="number"
接收关键事件和其他事件没有收到任何事件。
dialog_test.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<EditText
android:id="@+id/pass1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="inputType text (receives key events)"
android:inputType="text"/>
<EditText
android:id="@+id/pass2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="inputType number (doesn't receive key events)"
android:inputType="number"/>
</LinearLayout>
TestDialog.java
public class TestDialog extends Dialog {
public TestDialog(final Context context) {
super(context);
this.setContentView(R.layout.dialog_test);
this.setCanceledOnTouchOutside(false);
this.setOnKeyListener(new Dialog.OnKeyListener() {
@Override
public boolean onKey(final DialogInterface arg0, final int keyCode,
final KeyEvent event) {
// This listener is consuming all the events
return true;
}
});
}
}
为什么EditText
当 inputType
时接收关键事件是 text
尽管Dialog.OnKeyListener
消耗所有事件?
编辑:我正在 BQ Aquaris M5 上的 Android 5.1.1 测试中使用 Google 键盘
最佳答案
因为软件键盘不发送按键事件。他们通过 InputConnection 发送编辑命令。如果你想拦截这些,你需要子类化EditText并覆盖onCreateInputConnection中发送到键盘的InputConnection。
或者,如果您只想查看键盘上的内容,请使用 TextWatcher。
关于java - 当 inputType 为文本时,EditText 接收按键事件,尽管 Dialog.OnKeyListener 消耗了所有事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36089882/