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.            
  26.         highLightView.setText(style);     
  27.     }   
  28.        
  29. }  

相关内容