我最近购买了专业的Android4ApplicationDevelopment,我有一个关于第一个“待办事项列表”项目的问题(用户在EditText中键入某些内容,按enter并在添加到ListView之前输入文本):
一切都正常工作,但一旦我将目标SDK设置为16(4.1)或更高版本,当我按enter键时,onKeyListener就不会启动。为什么会这样,有没有办法解决这个问题?
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;
}
});谢谢您:)
发布于 2013-08-10 22:53:07
我认为你应该使用setOnEditorActionListener。
XML布局中的YOur EditText:
<EditText
android:id="@+id/myEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone" />你的行动:
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;
}
});您可以使用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
}
});https://stackoverflow.com/questions/18166917
复制相似问题