How to highlight TextView in Android

醉酒当歌 提交于 2019-12-23 02:35:02

问题


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.

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);


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/30484412/how-to-highlight-textview-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!