我想知道用户何时输入空格字符,以便我知道更新撤消列表。
使用onKeyListener
在虚拟键盘上不起作用(从概念上讲,这是错误的方法,我不在乎用户如何输入该空间,他可能已经粘贴了该空间)
TextWatcher
仅提供全文,采用字符串的最后一个字符无济于事。用户最好在中间输入。如何获取最后插入的字符?
答案 0 :(得分:3)
尝试一下:它应该为您解决。您可能需要添加更多错误检查。
edittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
//Char at newly inserted pos.
String str = s.charAt(start + before);
}
@Override
public void afterTextChanged(Editable editable) {
}
});
答案 1 :(得分:1)
et1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@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
}
});
答案 2 :(得分:0)
您可以比较TextChanged
事件之前和之后的字符串,以便查看发生了什么变化。此函数返回键入或删除的最后一个字符。
oldStr
在beforeTextChanged
中设置,而newStr
在onTextChanged
中设置。
这还会返回最后一个已删除字符。
public char lastCharTyped(String oldStr, String newStr){
String shorter, longer;
//find which string is shorter so that we don't end up out of bounds
if (oldStr.length()<newStr.length() ) {
shorter = oldStr;
longer = newStr;
} else {
shorter = newStr;
longer = oldStr;
}
//find the first character that is different and return it
for (int i = 0; i < shorter.length(); i++) {
if (longer.charAt(i) != shorter.charAt(i)) return longer.charAt(i);
}
//if no characters are different then return the last char of the longer string
//this means that the undo will be saved if the last char the user erased is a space
Log.d("longer",longer);
return(longer.charAt(longer.length()-1));
}
答案 3 :(得分:0)
以下是在文本中输入“#”(特殊字符)时对“执行某些操作”的答案。
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//do nothing
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//do nothing
}
@Override
public void afterTextChanged(Editable s) {
String string = s.toString();
if(string.contains("#")){
//do something
}
}
});