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

今日看到一本书上写了关于如何同时为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

24d809a87ee58bc53200c5ea6ccf470b.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值