需求:搜索TextView里面的關(guān)鍵字,并高亮顯示。
實現(xiàn)方法:
利用SpannableString 的特性,搜索TextView的要顯示的字符串,將相應(yīng)的關(guān)鍵字標(biāo)記為高亮
設(shè)計到的api
1. SpannableString
這是一個很奇妙的東西,利用他你可以實現(xiàn)qq聊天記錄自動替換表情文字的效果。當(dāng)然,這里我們只要將文字設(shè)計成高亮就可以了
2. 這里有個api函數(shù),
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
.
這個函數(shù)的object是給定的樣式,或者替換什么的,start和end指定了采用樣式的位置,flags我不知道是什么,這里用源碼里面的Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
3. 搜索方法,這里只是一個簡單的測試,用正則實現(xiàn)的搜索。
上代碼
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);
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);
要是大數(shù)據(jù)量的時候,每次搜索都重新setText可能效率上非常不好,這里提供一個看過源碼的建議,在一次setText(spannable s) 之后,每次getText獲取的就是spannable了,所以不用每次更改和重新載入數(shù)據(jù),直接更改就可以了。
參考
http://yuanzhifei89.iteye.com/blog/983944 這個頁面有些各種各樣的樣式和實現(xiàn)點(diǎn)擊跳轉(zhuǎn)的方法即Linkify