问题
how can i add Char such as this dash '-' after each change in edtitext for example if the user enter A then the text in edittext will be A- then the user will complete and enter Char B then the edittext will be A-B How to implement this ? thanks
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){
}
回答1:
You are having infinite loop as described in 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.
So all you have to do is just imposing a condition to avoid infinite loop. For example,
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) {
}
});
回答2:
Add a TextWatcher, using addTextChangedListener().
回答3:
Append the -
char in beforeTextChagned
name = (EditText)findViewById(R.id.editText1);
name.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
name.setText(s+"-");
}
public void afterTextChanged(Editable s){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
}
回答4:
name = (EditText)findViewById(R.id.editText1);
name.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
try{
name.setText(s.toString()+"-");
}catch(exception e)
{
e.printStackTrace();
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){
}
来源:https://stackoverflow.com/questions/7459966/android-change-edittext-after-each-change