问题
I have two edittext fields that i am using to display results of mathematical functions. I have two problems. I want to edit text to have a value of zero in two scenarios: 1st: I want the edit text value to automatically become zero if the edit text is empty
2nd: if a user erases field values till the edit text is empty.
UPDATE: The 1st problem I can sort with a setText() or android:text="0" but when trying to also solve the 2nd it becomes tricky
回答1:
Try something like this:
final EditText et = new EditText(this);
et.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if(et.getText().length() == 0){
et.setText("0");
}
}
});
回答2:
yourEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
if(yourEditText.getText().length() == 1 && yourEditText.getText().toString().trim().equals("0")){
yourEditText.setText("");
}
}else {
if(yourEditText.getText().length() == 0){
yourEditText.setText("0");
}
}
}
});
回答3:
use TextWatcher as folow :
yourEditText.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
}
});
i hope this will help :)
来源:https://stackoverflow.com/questions/31804956/setting-edittext-value-to-zero-when-empty-and-removing-zero-when-any-entry-is-ma