我正在 android 中开发一个应用程序,并想开发一种方法来捕获您在框中键入的文本,但不希望用户按下任何按钮,但是在文本写在框上的那一刻,采取几秒钟后获得文本,然后将其与其他文本进行比较。
问问题
48 次
3 回答
1
您可以使用EditText.addTextChangedListener()方法来侦听 EditText 文本更改。
您可以检查此示例实现:
editText = (EditText) findViewById(R.id.edit_text);
editText.addTextChangedListener(new TextWatcher(){
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = s.toString();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
}
于 2015-02-17T18:53:16.997 回答
0
如果将 onTextChangedListener 添加到 EditText,它将如下所示:
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
String text = txtMessage.getText().toString();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
于 2015-02-17T18:54:34.723 回答
0
TextWatcher
您可以向您添加一个EditText
并创建一个异步任务并将其发送到睡眠所需的时间,然后使用来自EditText
. 如果在任务仍在运行时文本中有任何更改,则取消任务并开始一个新任务,如下所示:
private UpdateFilterTask currentFilterTask = null;
private class UpdateFilterTask extends AsyncTask {
private String mInputText;
public UpdateFilterTask(String inputText){
this.mInputText = inputText;
}
@Override
protected Object doInBackground(Object[] params) {
try {
// Set the desired amount of time to wait in here, right now is 5 secs
Thread.sleep(5000);
} catch (InterruptedException e) {
return false;
}
if(this.isCancelled()){
return false;
}
return true;
}
@Override
protected void onPostExecute(Object o) {
Boolean didFinish = (Boolean) o;
if(didFinish){
// Do whatever you like with the mInputText
}
}
}
private class SearchTextWatcher implements TextWatcher {
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override public void afterTextChanged(Editable s) {}
@Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
if(currentFilterTask != null){
// If there was a running task previously, interrupt it
currentFilterTask.cancel(true);
currentFilterTask = null;
}
if(s.toString().trim().isEmpty()){
// Return to the original state as the EditText is empty now
return;
}
currentFilterTask = new UpdateFilterTask(s.toString());
currentFilterTask.execute();
}
}
于 2015-02-17T19:51:20.780 回答