简体   繁体   中英

EditText in multi-color

I am working on an Android application.

Now I want take input from user into an EditText. I want display the text after the last fullstop in black color and text before last full stop in red color.

For example, If user types below sentence in EditText:

'my name is john.I am from India.I Love Android'

I want to show the 'I love Android ' in black and first parts of the sentence in red.

Is there any way to do that?

Use SpannableString to apply attributes to your text. Here blog entry you may want to read: http://www.chrisumbel.com/article/android_textview_rich_text_spannablestring .

Listen to changes in text by:

    editText.addTextChangedListener(new TextWatcher() { 
        public void afterTextChanged(Editable s) { 
            if (!colorHasSet) {
                makeColorText();
            }
            colorHasSet = false;
        }
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
    });   

then declare a function to colorize text by using the tutorial which WebnetMobile linked to.

public void makeColorText() {
     SpannableString ss = new SpannableString(textEdit.getText());
    // customize ss here
    // ...
    colorHasSet = true;
    editText.setText(ss);
}

flag boolean variable colorHasSet should be defined to prevent stackOverflowException.

this is not a complete WYSIWYG editor with instant colored text, and you should do some hacks to make it complete and suitable to your needs, that is left to be done by yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM