Question

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.

Was it helpful?

Solution

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) {

        }
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top