将不同的字体和颜色设置为TextView的一部分

Arc*_*pgc 8 android typeface spannablestring

我试过这个:

String s = "Some big string"
SpannableStringBuilder sb = new SpannableStringBuilder(s);
//normal font for 1st 9 chars
sb.setSpan(robotoRegular, 0,9,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
//bold font for rest of the chars
sb.setSpan(robotoBold, 9,s.length(),Spannable.SPAN_INCLUSIVE_INCLUSIVE);
//also change color for rest of the chars
sb.setSpan(new ForegroundColorSpan(Color.BLACK), 9,s.length(),Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(sb);
Run Code Online (Sandbox Code Playgroud)

但这没效果.

它只需要最新的setSpan,即..,Text颜色正在改变但不是字体.

Ben*_*oli 34

你必须用一个TypefaceSpan而不是一个Typeface.

但是,由于您使用的是自定义字体,因此需要进行扩展TypefaceSpan.

看看这个答案并创建CustomTypefaceSpan课程.

现在执行以下操作:

Typeface robotoRegular = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.ttf");
Typeface robotoBold = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Bold.ttf");

TypefaceSpan robotoRegularSpan = new CustomTypefaceSpan("", robotoRegular);
TypefaceSpan robotoBoldSpan = new CustomTypefaceSpan("", robotoBold);

// normal font for 1st 9 chars
sb.setSpan(robotoRegularSpan, 0, 9, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
// bold font for rest of the chars
sb.setSpan(robotoBoldSpan, 9, s.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
// also change color for rest of the chars
sb.setSpan(new ForegroundColorSpan(Color.BLUE), 9, s.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(sb);
Run Code Online (Sandbox Code Playgroud)