我正在创建一个带有拦截一些键的Dialog.OnKeyListener
的Dialog
。
出于测试目的,我的onKey
方法始终返回true
这意味着我的Dialog.OnKeyListener
正在使用所有关键事件。
我的Dialog
中有一个EditText
,我发现如果我设置为text
以外的inputType
类型(例如number
),EditText
不会收到任何关键事件并且表现得像不可编辑(正如预期的那样,因为我的Dialog.OnKeyListener
正在使用所有事件),但是如果我将inputType
设置为inputType="text"
, EditText
接收所有关键事件(可编辑)。
对于我的示例,我有一个Dialog
,其中有一个OnKeyListener
使用所有事件和两个EditText
,一个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>
测试对话框.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;
}
});
}
}
尽管Dialog.OnKeyListener
使用所有事件,但EditText
为什么在text
inputType
时仍会收到密钥事件?
编辑:我正在使用谷歌键盘在Android 5.1.1测试BQ Aquaris M5
因为软件键盘不发送键事件。 它们通过 InputConnection 发送编辑命令。 如果要截获这些内容,则需要对 EditText 进行子类化,并覆盖在 onCreateInputConnection 中发送到键盘的 InputConnection。
或者,如果您只想查看键盘上的内容,请使用 TextWatcher。