TextView高亮显示

本文介绍如何使用SpannableStringBuilder和ForegroundColorSpan实现TextView中特定文本的高亮显示,通过实例展示了设置高亮颜色的方法。

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

TextView高亮显示

TextView的高亮显示主要用到的是SpannableStringBuilder类的setSpan()方法,这个方法有4个参数:

public voidsetSpan(Objectwhat, intstart, intend, intflags) {

       

    }

what:高亮颜色。。。(ForegroundColorSpan,URLSpan,StyleSpan,StrikethroughSpan,UnderlineSpan,ImageSpan)

start:开始字符位置

end:结束字符位置

flags:类别(例子这里输入前后都不包括)

如:

spannable.setSpan(newForegroundColorSpan(Color.RED), 2, 4,

              SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);

 

代码展示:

package lyx.feng.other;

 

import lyx.feng.simpletextdemo.R;

import android.app.Activity;

import android.graphics.Color;

import android.os.Bundle;

import android.text.SpannableStringBuilder;

import android.text.style.ForegroundColorSpan;

import android.widget.TextView;

 

public class SpinnableActivity extends Activity {

    private TextView tv = null;

    private TextView tv02 = null;

    private String info = "这是高亮显示的文字!";

    private String info02 = "这是默认显示的文字!";

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       super.setContentView(R.layout.spinnable);

       this.tv = (TextView) super.findViewById(R.id.spinnable_tv);

       this.tv02 = (TextView) super.findViewById(R.id.spinnable_tv02);

       SpannableStringBuilder spannable = new SpannableStringBuilder(info);

       spannable.setSpan(new ForegroundColorSpan(Color.RED), 2, 4,

              SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);

 

       this.tv.setText(spannable);

 

        this.tv02.setText(info02);

       this.tv02.setTextColor(Color.RED);

 

    }

}

 

效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值