Search code examples
androidandroid-edittexttextchanged

afterTextChanged deleting issue


I tried to set this up so that when I enter something into the EditText field, it will change the text color and set a variable to the value of the numbers entered. However, when I delete the characters from the field, it triggers an error that closes the app. I think I may either need to find an if statement that doesn't rely on length, or maybe use some of the other methods (onTextChanged, beforeTextChanged... I don't really know how to use either of those correctly though)

    public void afterTextChanged(Editable arg0) {
    if(arg0.length()>0){
        ageTag.setTextColor(Color.GREEN);
        ageEntered=true;
        ageInYears=Integer.parseInt(enterAge.getText().toString()); 
    }
}

Solution

    1. Implement the android.text.TextWatcher interface

    2. Bind a listener:

    enterAge.addTextChangedListener(this);