需求:搜索TextView里面的關鍵字,并高亮顯示。
實現方法:
利用SpannableString 的特性,搜索TextView的要顯示的字符串,將相應的關鍵字標記為高亮
設計到的api
1. SpannableString 
  這是一個很奇妙的東西,利用他你可以實現qq聊天記錄自動替換表情文字的效果。當然,這里我們只要將文字設計成高亮就可以了
2. 這里有個api函數,

         public abstract void setSpan (Object what, int start, int end, int flags)

Since: API Level 1

Attach the specified markup object to the range start…end of the text, or move the object to that range if it was already attached elsewhere. See Spanned for an explanation of what the flags mean. The object can be one that has meaning only within your application, or it can be one that the text system will use to affect text display or behavior. Some noteworthy ones are the subclasses of CharacterStyle and ParagraphStyle, and TextWatcher and SpanWatcher

這個函數的object是給定的樣式,或者替換什么的,start和end指定了采用樣式的位置,flags我不知道是什么,這里用源碼里面的Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
3. 搜索方法,這里只是一個簡單的測試,用正則實現的搜索。
上代碼
TextView tv = (TextView) findViewById(R.id.hello);
        SpannableString s 
= new SpannableString(getResources().getString(R.string.linkify));
    
        Pattern p 
= Pattern.compile("abc");
        
        
         Matcher m 
= p.matcher(s);

        
while (m.find()) {
            
int start = m.start();
            
int end = m.end();
            s.setSpan(
new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        tv.setText(s);
要是大數據量的時候,每次搜索都重新setText可能效率上非常不好,這里提供一個看過源碼的建議,在一次setText(spannable s) 之后,每次getText獲取的就是spannable了,所以不用每次更改和重新載入數據,直接更改就可以了。
參考
http://yuanzhifei89.iteye.com/blog/983944   這個頁面有些各種各樣的樣式和實現點擊跳轉的方法即Linkify