Android自定义view同时为文字和背景设置颜色的方法之ColorSpan、BackgroundColorSpan、CharacterStyle应用实例

今日看到一本书上写了关于如何同时为TextView设置文字颜色和背景颜色的方案,随手试验了一把,表示效果不错。事例如下

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.

        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);

展示效果如下截图示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值