OnKeyListener只检测返回键
问题描述:
我已经创建了最简单的Android项目,我可以使用OnKeyListener来测试EditText小部件中正在键入的内容。问题在于onKey方法只为返回键触发 - 没有其他方法。根据我的代码,可能会阻止OnKeyListener的工作?OnKeyListener只检测返回键
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setViewListeners();
}
private void setViewListeners() {
EditText et1 = (EditText)findViewById(R.id.text1);
EditText et2 = (EditText)findViewById(R.id.text2);
et1.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.i("INFO", "keyCode=" + keyCode);
return false;
}
});
}
}
而且布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
/>
<EditText
android:id="@+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
再次,唯一的按键,对此我得到一个日志语句是返回键(“键代码= 66”)。我还使用断点来确认这是代码执行的唯一时间。我的问题是什么?谢谢。
答
您应该使用的,而不是OnClickListener
mPostEditText.addTextChangedListener(watcher);
TextWatcher watcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence charsequence, int i, int j, int k) {
// TODO Auto-generated method stub
}
}
@Override
public void beforeTextChanged(CharSequence charsequence, int i, int j, int k) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable editable) {
// TODO Auto-generated method stub
}
};
烨TextWatcher,我已经走了这条路走了。 –
那是因为OnKeyListener没有注册字符键?该文件似乎表明它监听任何按键。 –