首页 > 系统 > Android > 正文

Android 实现不同字体颜色的TextView实现代码

2019-12-12 02:48:05
字体:
来源:转载
供稿:网友

Android 实现不同字体颜色的TextView

遇到的需求,mark一下。

实现代码:

package com.chuck.recyclerviewdemo;import android.content.Context;import android.graphics.Canvas;import android.text.SpannableStringBuilder;import android.text.Spanned;import android.text.style.ForegroundColorSpan;import android.util.AttributeSet;import android.widget.TextView;import java.util.List;/** * 项目名称:trunk * 类描述: * 创建人:Administrator * 创建时间:2015/12/10 14:05 * 修改人:Administrator * 修改时间:2015/12/10 14:05 * 修改备注: */public class DifferentColorTextView extends TextView{ public DifferentColorTextView(Context context) {  super(context); } public DifferentColorTextView(Context context, AttributeSet attrs) {  super(context, attrs); } public DifferentColorTextView(Context context, AttributeSet attrs, int defStyleAttr) {  super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) {  super.onDraw(canvas); } public void setDifferentColorText(List<String> text,List<Integer>colors){  setText(calculateResidue(text,colors)); } /**显示不同颜色*/ private SpannableStringBuilder calculateResidue(List<String> text, List<Integer>colors) {  if(text==null||colors==null){   return null;  }  StringBuilder sb =new StringBuilder();  for (int i=0;i<text.size();i++){   sb.append(text.get(i));  }  SpannableStringBuilder ssb=new SpannableStringBuilder(sb.toString());  int begin=0;  for (int i=0;i<text.size();i++){   ForegroundColorSpan mSpan = new ForegroundColorSpan(colors.get(i));   ssb.setSpan(mSpan,begin,begin+text.get(i).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);   begin=begin+text.get(i).length();  }  return ssb; }}

   实现同一textView,不同颜色。

        感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表