通过SpannableStringBuilder来实现,它就像html里边的元素改变指定文字的文字颜色或背景色

public class MainActivity extends Activity {     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        String str="这是设置TextView部分文字背景颜色和前景颜色的demo!";        int bstart=str.indexOf("背景");        int bend=bstart+"背景".length();        int fstart=str.indexOf("前景");        int fend=fstart+"前景".length();        SpannableStringBuilder style=new SpannableStringBuilder(str);         style.setSpan(new BackgroundColorSpan(Color.RED),bstart,bend,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);           style.setSpan(new ForegroundColorSpan(Color.RED),fstart,fend,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);         TextView tvColor=(TextView) findViewById(R.id.tv_color);        tvColor.setText(style);    }}

项目中代码:

//textview 设置部分颜色public SpannableStringBuilder  setPartColorText(String str){//使用SpannableStringBuilder类SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder(str);//确定部分颜色的位置int start=str.indexOf(content);int end=start+content.length();//确定颜色为红色ForegroundColorSpan mForeColor=new ForegroundColorSpan(Color.RED);//setspanspannableStringBuilder.setSpan(mForeColor, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);return spannableStringBuilder;}

AbsoluteSizeSpan(int size) ---- 设置字体大小,参数是绝对数值,相当于Word中的字体大小

RelativeSizeSpan(float proportion) ---- 设置字体大小,参数是相对于默认字体大小的倍数,比如默认字体大小是x, 那么设置后的字体大小就是x*proportion,这个用起来比较灵活,proportion>1就是放大(zoom in), proportion<1就是缩小(zoom out)
ScaleXSpan(float proportion) ---- 缩放字体,与上面的类似,默认为1,设置后就是原来的乘以proportion,大于1时放大(zoon in),小于时缩小(zoom out)

BackgroundColorSpan(int color) ----背景着色,参数是颜色数值,可以直接使用android.graphics.Color里面定义的常量,或是用Color.rgb(int, int, int)

ForegroundColorSpan(int color) ----前景着色,也就是字的着色,参数与背景着色一致TypefaceSpan(String family) ----字体,参数是字体的名字比如“sans", "sans-serif"等StyleSpan(Typeface style) -----字体风格,比如粗体,斜体,参数是android.graphics.Typeface里面定义的常量,如Typeface.BOLD,Typeface.ITALIC等等。

StrikethroughSpan----如果设置了此风格,会有一条线从中间穿过所有的字,就像被划掉一样




更多相关文章

  1. java回调C++
  2. android通过web service调用查询手机归属地代码
  3. Android(安卓)单选之史上最简单的ListView实现单选效果
  4. Android应用程序安装过程源代码分析(2)
  5. android快速实现沉浸式
  6. Android通过URL获取网络数据(2)
  7. android—调试命令service
  8. android Audio调试程序常用命令
  9. Android(安卓)常见问题解决记录

随机推荐

  1. Android下的串口通信实战之控制客显
  2. android TV 开发规范
  3. Android APP存活检测
  4. Android的引用计数(强弱指针)技术及一些
  5. 怎么用Fuzz技术巧妙的挖掘Android漏洞?And
  6. 谈谈怎么最快学好android(转)
  7. Android NDK(七):JNI异常处理
  8. 花式读取Android CPU使用率
  9. Android基础教程之---Android状态栏提醒(
  10. 专题:Android 移植到C#