Tinashe
Tinashe

Reputation: 3215

How to highlight TextView in Android

I would like to highlight a TextView and achieve the design shown below. Does anyone know how to achieve this using a TextView? I took this screenshot from an existing Android app.

enter image description here

By using this code I get results shown below, which is not what I want:

sp.setSpan(new BackgroundColorSpan(color), start, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

enter image description here

Upvotes: 1

Views: 6155

Answers (2)

Bidhan
Bidhan

Reputation: 10697

If I understand you correctly, you want to highlight the text with a light color? If that's the case, then simply change the transparency of the color. For example: change the first two FF of 0xFFFFFF00 to something like 80(50 % transparency). So, it would look like 0x80FFFF00.

TextView textView = (TextView)findViewById(R.id.textView1);
String  text = "Your String"; 
Spannable spanText = Spannable.Factory.getInstance().newSpannable(text);
spanText.setSpan(new BackgroundColorSpan(0x80FFFF00), 14, 19,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spanText);

Here's a relevant thread regarding hex color transparency.

Upvotes: 1

Yash Sampat
Yash Sampat

Reputation: 30611

You need to use a Spannable String:

TextView textView = (TextView)findViewById(R.id.textView1);
String  text = "Test"; 
Spannable spanText = Spannable.Factory.getInstance().newSpannable(text);
spanText.setSpan(new BackgroundColorSpan(0xFFFFFF00), 14, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spanText);

Try this. This will work.

Upvotes: 3

Related Questions