Swap
Swap

Reputation: 490

Android - Change Background Color of a part of String in EditText(Highlighting Text)

I'm making an app in which I there is an EditText and a ToggleButton. I want to create a highlighter mechanism with the help of these. For example, when the state of the ToggleButton is ON, the text that'll be entered in the EditText will have Green background as if it is being highlighted. Again, when the ToggleButton state will be changed to OFF, the text in the EditText will also stop getting highlighted immediately.

Please Help Me.

Thanks in Advance!!

Upvotes: 0

Views: 897

Answers (3)

Houcine
Houcine

Reputation: 24181

Simply you set onCheckedChangeListener on your ToggleButton to change the background of your EditText. Your code will be something like this :

toggleButtonHighLight.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton button, boolean isChecked) {
        if (checked) {
            //highlight the EditText by setting its background to green
            editText.setBackgroundResource(R.color.green);
        } else {
            //delete the highlight when the toggleButton is OFF
            editText.setBackgroundColor(android.R.color.white);
        }
    }
});

Upvotes: 0

atok
atok

Reputation: 5938

You can change the background color of part of the text using SpannableString as described here: Set color of TextView span in Android

Another way of doing the same thing is to load the text from HTML with the tag set to the background color you want.

Upvotes: 1

Zohra Khan
Zohra Khan

Reputation: 5302

To change the colour of text use

textElement.setTextColor(0xFF00FF00); //this is green colour

To change the colour of edit text use

textElement.setBackgroundColor(Color.MAGENTA);

For more information Check this link.

Upvotes: 0

Related Questions