我想在用户编辑完EditText时捕获一个事件。
怎么做呢?
发布于 2011-11-09 18:19:52
用户完成编辑后,将按Done
或Enter
((EditText)findViewById(R.id.youredittext)).setOnEditorActionListener(
new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
event != null &&
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
if (event == null || !event.isShiftPressed()) {
// the user is done typing.
return true; // consume.
}
}
return false; // pass on to other listeners.
}
}
);
发布于 2015-02-20 17:36:56
我个人更喜欢在打字结束后自动提交。下面是如何检测此事件的方法。
声明和初始化:
private Timer timer = new Timer();
private final long DELAY = 1000; // in ms
监听程序,例如onCreate()
EditText editTextStop = (EditText) findViewById(R.id.editTextStopId);
editTextStop.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(final CharSequence s, int start, int before,
int count) {
if(timer != null)
timer.cancel();
}
@Override
public void afterTextChanged(final Editable s) {
//avoid triggering event when text is too short
if (s.length() >= 3) {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO: do what you need here (refresh list)
// you will probably need to use
// runOnUiThread(Runnable action) for some specific
// actions
serviceConnector.getStopPoints(s.toString());
}
}, DELAY);
}
}
});
因此,当文本被更改时,计时器将开始等待下一次更改的发生。当它们发生时,计时器被取消,然后再次启动。
发布于 2011-11-09 18:25:40
您可以使用setOnKeyListener或如下所示的textWatcher完成此操作:
设置文本观察器editText.addTextChangedListener(textWatcher);
然后调用
private TextWatcher textWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//after text changed
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
https://stackoverflow.com/questions/8063439
复制相似问题