我如何在 edtitext 的每次更改后添加 Char,例如这个破折号 '-' 例如,如果用户输入 A,则 edittext 中的文本将为 A- 然后用户将完成并输入 Char B,然后 edittext 将为A-B 如何实现?谢谢
name = (EditText)findViewById(R.id.editText1);
name.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
name.setText("-");
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){
}
最佳答案
Android Doc 中描述的是无限循环
but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively.
所以你所要做的只是强加一个条件来避免无限循环。例如,
name.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if(s.charAt(s.length()-1)!='-'){
s.append("-");
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
关于Android-每次更改后更改Edittext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7459966/