简体   繁体   中英

Formatting EditText and TextView with SpannableStringBuilder

I have a TextView that displays texts retrieved from db and some parts of the texts are marked as comment.

Here is sample.....

// CREATE A VARIABLE AT THE CLASS LIKE THIS...
private static int delay = 4000; //4Secs

/*NOW THE DELAY METHOD*/
new Handler().postDelayed(new Runnable() {

    @Override
    public void run() {
        // DECLARE ACTIONS TO BE DELAYED HERE...
    }
}, delay);

Now i want all the single and multi line comment texts to have a different textColor. How do i go about this?

If you format the String with html's font-color property then pass it to the method Html.fromHtml(your text here)

String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));

or You can prints lines with multiple colors without HTML as:

SpannableStringBuilder builder = new SpannableStringBuilder();

SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);

SpannableString str2= new SpannableString("Text2");
str2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str2.length(), 0);
builder.append(str2);

TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText( builder, TextView.BufferType.SPANNABLE);

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