android TextView 實現關鍵字高亮

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

         publicabstractvoidsetSpan(Object what, int start, int end, int flags)

Attach the specified markup object to the range start…endof the text, or move the object to that range if it was alreadyattached elsewhere. See Spanned for an explanation ofwhat the flags mean. The object can be one that has meaning onlywithin your application, or it can be one that the text system willuse to affect text display or behavior. Some noteworthy ones arethe subclasses of CharacterStyle andParagraphStyle, andTextWatcher andSpanWatcher

這個函數的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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章