搜索关键字变红,指定字段变色 一行代码简单集成 搜索关键字变红,Android字体变红,指定字段变红

 搜索关键字变红,指定字段变色

有时候我们搜索中的关键字需要变红或者变为别的颜色,我自己重写了textview。使用起来特别方便
使用步骤

1,把下面自定义的MyTextView 复制到项目中

import android.content.Context; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; import android.widget.TextView;

import java.util.ArrayList; import java.util.List;

//制定字体变色,自定义textview public class MyTextView extends TextView {

public MyTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public void setSpecifiedTextsColor(String text, String specifiedTexts, int color) {
    List<Integer> sTextsStartList = new ArrayList<>();

    int sTextLength = specifiedTexts.length();
    String temp = text;
    int lengthFront = 0;//记录被找出后前面的字段的长度
    int start = -1;
    do {
        start = temp.indexOf(specifiedTexts);

        if (start != -1) {
            start = start + lengthFront;
            sTextsStartList.add(start);
            lengthFront = start + sTextLength;
            temp = text.substring(lengthFront);
        }

    } while (start != -1);

    SpannableStringBuilder styledText = new SpannableStringBuilder(text);
    for (Integer i : sTextsStartList) {
        styledText.setSpan(
                new ForegroundColorSpan(color),
                i,
                i + sTextLength,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    setText(styledText);
}

}

2,使用只需要一行代码就可以完事 public class TextActivity04 extends Activity { private MyTextView textView;

public String result = "关键字变色,特别简单,只需要一行代码,就可以实现关键字变红";

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_04_layout);

    textView = (MyTextView)findViewById(R.id.tv);
    textView.setSpecifiedTextsColor(result, "关键字", Color.parseColor("#FF0000"));
    /*
        textView.setSpecifiedTextsColor(result, "关键字", Color.parseColor("#FF0000"))中result可以换成你的搜索结果
        关键字直接换成你的EditText中输入的关键字就可以啦

    */
}

}

效果图




源码下载地址

https://github.com/qiushi123/BlurBehindActivity
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值