1

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

Tinashe
  • 3,115
  • 3
  • 25
  • 23

2 Answers2

3

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.

Yash Sampat
  • 30,051
  • 12
  • 94
  • 120
  • Please check my updated question, BackgroundColorSpan results in something different from what I really want. – Tinashe May 28 '15 at 06:14
  • What about letting the style apart from the UI? – joninx May 28 '15 at 06:16
  • @Tinashe Did you ever get an answer? The answers above do not address your question about the needed white space. I have the same problem and have not been able to find an answer. – Bob Lissner Dec 03 '16 at 00:10
  • @BobLissner Unfortunately I could not find an answer. But I assume this can only be achieved with css – Tinashe Dec 19 '16 at 05:45
1

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.

Community
  • 1
  • 1
Bidhan
  • 10,607
  • 3
  • 39
  • 50
  • this is way better than what I had, Thanks a lot. but still it does not leave the white spaces in-between the sentences as it is in the image. – Tinashe May 28 '15 at 07:04