我有EditText
。当用户在更改EditText
时按 Enter 键时,我想做某事。我怎样才能做到这一点?
最简单的方法:
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
答案 0 :(得分:6)
文本观察器的示例代码
your_edittext.addTextChangedListener(new InputValidator());
private class InputValidator implements TextWatcher {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
}
}
答案 1 :(得分:4)
首先,创建一个OnEditorActionListener
(例如,作为私有实例变量):
private TextView.OnEditorActionListener mEnterListener =
new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) {
/* If the action is a key-up event on the return key, do something */
}
return true;
});
然后,设置监听器(即在onCreate
方法中):
EditText mEditText = (EditText) findViewById(...);
mEditText.setOnEditorActionListener(mEnterListener);
答案 2 :(得分:1)
另一种选择是:
your_edittext.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
});
答案 3 :(得分:0)
您需要使用TextWatcher来实现此目的。以下是有关如何使用TextWatcher和Android textwatcher API的示例。
答案 4 :(得分:-4)
your_edittext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//do something
}
});