我正在尝试获取用户对EditText所做的修改,无论是插入还是删除。我使用TextWatcher但是我得不到正确的结果,而且有时“getChar(start,end)在开始之前已经结束”错误。
editText = (EditText) findViewById(R.id.MyEditText);
editText.addTextChangedListener(new TextWatcher() {
@override
public void afterTextChanged(Editable s){}
@override
public void beforeTextChanged(CharSequence s, int start, int count, int after){
showToast("text removed: " + s.subSequence(start, count));
}
@override
public void onTextChanged(CharSequence s, int start, int before, int count){
showToast("text added: " + s.subSequence(start, count));
}
}
正如您所看到的,我使用beforeTextChanged
来获取用户删除的任何文本,并onTextChanged
进行插入。请在这里阐明一些。谢谢!
编辑:
我似乎想通了......这很愚蠢:s.subSequence(start, count))
应该是s.subSequence(start, start+count))
答案 0 :(得分:0)
只需将您的功能保留在afterTextChanged
内,看看会发生什么
示例代码
seachbox.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
fillData(SEARCH_ORDER ,s.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
});
我希望它会起作用
答案 1 :(得分:0)
试试这个,我不确定你是否想要剩余的单词(插入/更新后)或字母(添加/删除)。
public class MainActivity extends Activity implements TextWatcher {
private EditText myEditText;
private String inputText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myEditText = (EditText) findViewById(R.id.testEditText);
myEditText.addTextChangedListener(this);
}
@Override
public void afterTextChanged(Editable s) {
if (inputText.length() < s.toString().length()) {
Toast.makeText(
this,
("Text Added: " + s.toString().substring(inputText.length(),
s.toString().length())), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(
this,
("Text Removed: " + inputText.substring(s.toString().length(),
inputText.length())), Toast.LENGTH_SHORT).show();
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
inputText = s.toString();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}