【发布时间】:2011-09-12 17:55:56
【问题描述】:
我需要知道 EditText 是否被更改,而不是用户是否在字段中输入了一些文本,而只需要知道 String 是否被更改。
【问题讨论】:
我需要知道 EditText 是否被更改,而不是用户是否在字段中输入了一些文本,而只需要知道 String 是否被更改。
【问题讨论】:
你需要一个
TextWatcher
在这里查看它的实际效果:
EditText text = (EditText) findViewById(R.id.YOUR_ID);
text.addTextChangedListener(textWatcher);
private TextWatcher textWatcher = new 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) {
}
}
【讨论】:
如果你改变主意听击键,你可以使用 OnKeyListener
EditText et = (EditText) findViewById(R.id.search_box);
et.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
//key listening stuff
return false;
}
});
但 Johe 的答案正是你所需要的。
【讨论】:
这实际上对我有用
EditText text = (EditText) findViewById(R.id.YOUR_ID);
text.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(your_string.equals(String.valueOf(s))) {
//do something
}else{
//do something
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
【讨论】:
实现TextWatcher。它为您提供了三种方法,beforeTextChanged、onTextChanged 和 afterTextChanged。最后一个方法在发生变化之前不应该被调用,所以使用它是一件好事。
【讨论】: