[英]Android onKeyListener doesnt fire
I've recently bought Professional Android 4 Application Development , and I've got a question about the first "todo-list" project(the user types something in an EditText, presses enter and the Text entered before get added to a ListView): 我最近购买了Professional Android 4 Application Development ,并且对第一个“ todo-list”项目有疑问(用户在EditText中键入内容,然后按Enter和Enter,然后将其添加到ListView中):
everything works as it should, but as soon as I set the target SDK to 16(4.1) or higher the onKeyListener doesn't fire when I press enter. 一切正常,但将目标SDK设置为16(4.1)或更高版本时,按Enter键时不会触发onKeyListener。 Why is that and is there a way to solve this? 为什么会这样,有办法解决吗?
myEditText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) || (keyCode == KeyEvent.KEYCODE_ENTER)) {
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText("");
return true;
}
return false;
}
});
Thank you :) 谢谢 :)
I think you should use setOnEditorActionListener
. 我认为您应该使用setOnEditorActionListener
。
YOur EditText
in XML layout: 我们的XML布局中的EditText
:
<EditText
android:id="@+id/myEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone" />
Your action: 您的动作:
EditText myEditText = (EditText) findViewById(R.id.myEditText);
myEditText
.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView view, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// Your action
}
return true;
}
});
You can use TextWatcher
: 您可以使用TextWatcher
:
EditText myEditText = (EditText) findViewById(R.id.myEditText);
myEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (s.toString().substring(start).contains("\n")) {
// YOur action
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// empty
}
@Override
public void afterTextChanged(Editable s) {
// empty
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.