Android中字符串片段高亮

1. 引言

     在Android 中,使某个字符串中的某个单词或汉字高亮,效果图及代码实现如下。

2. 效果图

     高亮

 

3. 功能实现

    1. 主界面(main.xml)实现:

  1. <?xml version= "1.0"  encoding= "utf-8" ?>   
  2. <LinearLayout xmlns:Android  =  "http://schemas.android.com/apk/res/android"   
  3.     Android :orientation =  "vertical"   
  4.     Android :layout_width =  "fill_parent"   
  5.     Android :layout_height =  "fill_parent"   
  6.     >   
  7.        
  8.     <TextView   
  9.         Android :id =  "@+id/highLight"   
  10.         Android :layout_width =  "wrap_content"   
  11.         Android :layout_height =  "wrap_content"   
  12.         />   
  13. </LinearLayout>   

    2. 主Activity实现:

 
  1. package  com.focus.fishme;   
  2. import  Android .app.Activity;   
  3. import  Android .graphics.Color;   
  4. import  Android .os.Bundle;   
  5. import  Android .text.Spannable;   
  6. import  Android .text.SpannableStringBuilder;   
  7. import  Android .text.style.BackgroundColorSpan;   
  8. import  Android .widget.TextView;   
  9. public   class  HighLightActivity  extends  Activity {   
  10.        
  11.      @Override   
  12.      public   void  onCreate(Bundle savedInstanceState) {   
  13.          super .onCreate(savedInstanceState);   
  14.         setContentView(R.layout.main);   
  15.            
  16.         TextView highLightView = (TextView) findViewById(R.id.highLight);   
  17.            
  18.         String highLightStr =  "HighLight MaYingCai" ;     
  19.         String highLight =  "MaYingCai" ;     
  20.            
  21.          int  start = highLightStr.indexOf(highLight);     
  22.            
  23.         SpannableStringBuilder style =  new  SpannableStringBuilder(highLightStr);     
  24.         style.setSpan( new  BackgroundColorSpan(Color.RED), start, start + highLight.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);   
  25.          /// style.setSpan(new ForegroundColorSpan(Color.RED),3,8,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  26.         highLightView.setText(style);     
  27.     }   
  28.        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值