Rúben Dias Rúben Dias - 3 months ago 30
Android Question

How can I compare two values using the TextWatcher

I'm using a TextWatcher to receive every letter from a EditText in real-time, and I would like to compare the EditText text, to a specific String.

I would like to change the color from the EditText when both values are different.

I already tried to implement my ideas, but is not working properly, I don't receive any error, the text just stays red all the time even when the first letters are equal.

My code:

public void onTextChanged(CharSequence s, int start, int before, int count) {

for(int i = 0; i < getString().length();i++){

if (String.valueOf(s).equals(getString().charAt(i))) {

mEditText.setTextColor(Color.GREEN);

} else {

mEditText.setTextColor(Color.RED);

}

}



}


Thank you.

Answer

try using edittext's string directly on textwatcher.

if(mEditText.getText().toString.equals("YourString") {
    mEditText.setTextColor(Color.GREEN);
} else {
    mEditText.setTextColor(Color.RED);
}