Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android TextView text background color

How can I achieve such an effect with an Android TextView. It looks somehow like selected text and I couldn't find something similar in the API.

This is not a background color for the view, but a background color only for the text. You can see how it stops at line breaks and has a thin white line between text lines.

Screenshot

like image 571
Ole Krüger Avatar asked Mar 23 '13 03:03

Ole Krüger


People also ask

How do I change the text color on my Android?

Open your device's Settings app . Text and display. Select Color correction. Turn on Use color correction.


2 Answers

<TextView
android:background="#0000FF"
android:textColor="#FFFFFF" />

Would define a TextView with a blue background and white text...is that what you need?

like image 151
Tyler MacDonell Avatar answered Sep 19 '22 19:09

Tyler MacDonell


As far as I can see, there's no 'nice' way of doing this without overriding TextView and drawing custom paints on the view which includes the gap colour.

Even setting the lineSpacingExtra property only expands the background colour.

You could also potentially look into creating a custom spannable and use it like

Spannable str = new SpannableStringBuilder("How can I achieve such an effect with an Android TextView. It looks somehow like selected text and I couldn't find something similar in the API.");
str.setSpan(new NewSpannableClass(), 0, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
((TextView)findViewById(R.id.text)).setText(str);

Where NewSpannableClass is the custom spannable.

Seeing as many people are lazy to look up how to make custom spannables, here's an example

public class CustomSpannable extends ClickableSpan
{
    @Override public void updateDrawState(TextPaint ds)
    {
        super.updateDrawState(ds);
        ds.setUnderlineText(true);
    }
}

This example will underline the text. Use TextPaint to change the look of the spanned text.

like image 30
ScruffyFox Avatar answered Sep 17 '22 19:09

ScruffyFox