今日看到一本书上写了关于如何同时为TextView设置文字颜色和背景颜色的方案,随手试验了一把,表示效果不错。事例以下java
package com.example.zhouxueli.myapplication;
import android.text.TextPaint;
import android.text.style.CharacterStyle;
public class ColorSpan extends CharacterStyle {
private int mTextColor;
private int mBackgroundColor;
public ColorSpan(int mTextColor, int mBackgroundColor) {
this.mTextColor = mTextColor;
this.mBackgroundColor = mBackgroundColor;
}
//该方法会在系统开始绘制须要设置样式的字符串以前被调用,以便绘制要修改文字的属性
@Override
public void updateDrawState(TextPaint tp) {
tp.bgColor=mBackgroundColor;
tp.setColor(mTextColor);
}
}
以下我是直接放在测试Activity 的onCreate()方法中的,其中使用到的textView只是我简单省事,直接在Activity的布局页面xml文件中放置了一个只有宽高属性的textView.android
TextView textView=findViewById(R.id.tvSelf);
String text="\n\n";
SpannableString spannableString=new SpannableString(text);
int start = 6;
int end = 12;
BackgroundColorSpan backgroundColorSpan=new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(backgroundColorSpan,start,end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
start = 14;
ColorSpan colorSpan = new ColorSpan(Color.RED,Color.BLUE);
spannableString.setSpan(colorSpan,start,text.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
展现效果以下截图示例app