Android中字符串片段高亮
16lz
2022-03-09
1. 引言
在Android 中,使某个字符串中的某个单词或汉字高亮,效果图及代码实现如下。
2. 效果图
3. 功能实现
1. 主界面(main.xml)实现:
- <?xmlversion= "1.0" encoding= "utf-8" ?>
- <LinearLayoutxmlns:Android = "http://schemas.android.com/apk/res/android"
- Android :orientation= "vertical"
- Android :layout_width= "fill_parent"
- Android :layout_height= "fill_parent"
- >
- <TextView
- Android :id= "@+id/highLight"
- Android :layout_width= "wrap_content"
- Android :layout_height= "wrap_content"
- />
- </LinearLayout>
2. 主Activity实现:
- package com.focus.fishme;
- import Android .app.Activity;
- import Android .graphics.Color;
- import Android .os.Bundle;
- import Android .text.Spannable;
- import Android .text.SpannableStringBuilder;
- import Android .text.style.BackgroundColorSpan;
- import Android .widget.TextView;
- public class HighLightActivity extends Activity{
- @Override
- public void onCreate(BundlesavedInstanceState){
- super .onCreate(savedInstanceState);
- setContentView(R.layout.main);
- TextViewhighLightView=(TextView)findViewById(R.id.highLight);
- StringhighLightStr= "HighLightMaYingCai" ;
- StringhighLight= "MaYingCai" ;
- int start=highLightStr.indexOf(highLight);
- SpannableStringBuilderstyle= new SpannableStringBuilder(highLightStr);
- style.setSpan( new BackgroundColorSpan(Color.RED),start,start+highLight.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- /////////// style.setSpan(new ForegroundColorSpan(Color.RED),3,8,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- highLightView.setText(style);
- }
- }
更多相关文章
- Android(安卓)代码执行Linux Shell小记
- android 横向滚动屏幕实现(1)
- Android(安卓)开源项目分类汇总
- Android(安卓)实现跑马灯效果
- Android实现发送短信功能实例详解
- android全屏去掉title栏的多种实现方法
- Android中字符串片段高亮
- android中分割线的实现
- 浅谈Java中Collections.sort对List排序的两种方法