android textview改变部分文字的颜色和string.xml中文字的替换
16lz
2021-01-25
阅读更多
一:TextView组件改变部分文字的颜色:
TextView textView = (TextView)findViewById(R.id.textview);//方法一:textView.setText(Html.fromHtml("红色其它颜色"));//方法二: String text = "获得银宝箱!"; SpannableStringBuilder style=new SpannableStringBuilder(text); style.setSpan(new BackgroundColorSpan(Color.RED),2,5,Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //设置指定位置textview的背景颜色 style.setSpan(new ForegroundColorSpan(Color.RED),0,2,Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //设置指定位置文字的颜色 textView.setText(style);
二:android string.xml文件中的整型和string型代替:
String text = String.format(getResources().getString(R.string.baoxiang), 2,18,"银宝箱");
对应的string.xml文件参数:
您今天打了%1$d局,还差%2$d局可获得%3$s!
%1$d表达的意思是整个name=”baoxiang”字符串中,第一个整型
在项目开发者,经常需要把以上两者结合起来使用。可以避免很多textview的拼接,如下所示:
TextView textView = (TextView)findViewById(R.id.testview);String text = String.format(getResources().getString(R.string.baoxiang), 2,18,"银宝箱"); int index[] = new int[3]; index[0] = text.indexOf("2"); index[1] = text.indexOf("18"); index[2] = text.indexOf("银宝箱"); SpannableStringBuilder style=new SpannableStringBuilder(text); style.setSpan(new ForegroundColorSpan(Color.RED),index[0],index[0]+1,Spannable.SPAN_EXCLUSIVE_INCLUSIVE); style.setSpan(new ForegroundColorSpan(Color.RED),index[1],index[1]+2,Spannable.SPAN_EXCLUSIVE_INCLUSIVE); style.setSpan(new BackgroundColorSpan(Color.RED),index[2],index[2]+3,Spannable.SPAN_EXCLUSIVE_INCLUSIVE); textView.setText(style);
更多相关文章
- Android(安卓)使用OpenGLES 的粒子系统
- android 控件在不同状态下的内容样式与背景样式
- Android(安卓)自定义EditText输入框 带清空按钮
- Android(安卓)中CoordinatorLayout+AppBarLayout实现滚动头部悬
- Android(安卓)颜色渲染(十) ComposeShader组合渲染
- android 之View 一
- Android(安卓)给View添加一个点击的水波纹特效
- Android(安卓)Drawable 关于selector中state_pressed="true"的位
- 在Android中使用Google map