0

In my app, I want the users to give their answers in the form of text through edit text. So for the correct answer I want the letters to turn green (or red for incorrect) on the fly while typing.

For example, if the answer is DOG, I want the the text to turn green if the user types DOG dynamically. Even if the the first letter he types is D then I want the text color to be green. Only when the user's input text is not correct do I want it to be red. The text color should change on the fly while typing.

bjb568
  • 11,089
  • 11
  • 50
  • 71
Rahul RK
  • 15
  • 2
  • You could try using: [Using multiple text colors in Android's textview](http://stackoverflow.com/questions/10392163/using-multiple-text-colors-in-androids-textview-html-fromhtml) – Matan Dahan Mar 30 '14 at 20:04

1 Answers1

0

Create EditText and call addTextChangedListener for it supplying custom TextWatcher where you mostly need to override its onTextChanged.

In this method change your text color according to your logic.

Snapshot :

    mEditBox = (EditText) findViewById(R.id.my_edit_box_id);
    mEditBox.addTextChangedListener(new TextWatcher() {

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

            String currentText = mEditBox.getText().toString();
            // highligt correct answer in green
            if ("DOG".startsWith(currentText)) { // user starts typing "DOG"
                mEditBox.setTextColor(Color.GREEN);
            } else {
                mEditBox.setTextColor(Color.RED); // incorrect input
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
kiruwka
  • 9,250
  • 4
  • 30
  • 41
  • now when i run the app,at the first instance the text color is red for the answer "DOG" only when i erase it and type it again it turns green.so can u help me with a solution to change the text color at the first instance itself? – Rahul RK Mar 31 '14 at 06:47
  • Do you mean your editbox contains "default" text DOG initially ? – kiruwka Mar 31 '14 at 07:39
  • nope. when I type DOG initially FOR the first time the text color is red. only wen I erase it and type again it turns green. – Rahul RK Mar 31 '14 at 08:15
  • very strange, works fine for me. When do you call `addTextChangedListener` ? Can you make a breakpoint in `onTextChanged` and see that it is triggered when you start typing initially ? – kiruwka Mar 31 '14 at 09:02