android textview 设置多个颜色,Android开发笔记——TextView文本设置不同颜色

这段代码展示了如何在Android中通过 SpannableStringBuilder 和 ForegroundColorSpan 设置TextView的标题和内容颜色。它接受标题、内容、标题颜色ID和内容颜色ID作为参数,创建并设置Spannable对象到TextView。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.只贴代码,不解释,留作以后用/**

* @param tv             Display a message that include title and content

* @param title          Title of message

* @param content        Content of message

* @param titleColorID   The color id for Title

* @param contentColorID The color id for Content

*/

public static void colorForTextView(Context context, TextView tv, String title, String content,

int titleColorID, int contentColorID) {

if (content == null) {

content = "";

}

SpannableStringBuilder spannableBuilder = new SpannableStringBuilder();

ForegroundColorSpan titleColorSpan = new ForegroundColorSpan(ContextCompat.getColor(context, titleColorID));

ForegroundColorSpan contentColorSpan = new ForegroundColorSpan(ContextCompat.getColor(context, contentColorID));

spannableBuilder.append(title);

int temp = spannableBuilder.length();

spannableBuilder.setSpan(titleColorSpan, 0, temp, Spanned.SPAN_INCLUSIVE_INCLUSIVE);

spannableBuilder.append(content);

spannableBuilder.setSpan(contentColorSpan, temp, spannableBuilder.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);

tv.setText(spannableBuilder, TextView.BufferType.SPANNABLE);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值