我正在構建一個android應用程序,我解析一組數據並在listView中顯示。現在,當用戶搜索該數據集中的單詞時,我會突出顯示該文本視圖的單詞。如何在android中的textView中顯示高亮字符串?
現在的問題是,當這個搜索詞在開始它顯示爲文本視圖是最大行1,但如果它的最後一箇中間詞的段落突出顯示,但我想顯示在文本視圖中突出顯示的單詞與最大線1.
有什麼辦法來調整文本視圖中的字符串和顯示突出顯示的區域。
我正在構建一個android應用程序,我解析一組數據並在listView中顯示。現在,當用戶搜索該數據集中的單詞時,我會突出顯示該文本視圖的單詞。如何在android中的textView中顯示高亮字符串?
現在的問題是,當這個搜索詞在開始它顯示爲文本視圖是最大行1,但如果它的最後一箇中間詞的段落突出顯示,但我想顯示在文本視圖中突出顯示的單詞與最大線1.
有什麼辦法來調整文本視圖中的字符串和顯示突出顯示的區域。
你需要的是使用Spans。例如,您可以突出顯示一些文字,如下所示:
TextView textview = (TextView)findViewById(R.id.mytextview);
Spannable spannable = new SpannableString("Hello World");
spannable.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(spannable);
我已經嘗試了一個片段。希望這會幫助你。
final TextView sampleText =(TextView)findViewById(R.id.tv_sample_text);
EditText ed_texthere =(EditText)findViewById(R.id.ed_texthere);
final String fullText = sampleText.getText().toString();
ed_texthere.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String typedText = charSequence.toString();
if (typedText != null && !typedText.isEmpty()) {
int startPos = fullText.toLowerCase(Locale.US).indexOf(typedText.toLowerCase(Locale.US));
int endPos = startPos + typedText.length();
if (startPos != -1) {
Spannable spannable = new SpannableString(fullText);
ColorStateList blueColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.BLUE});
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null);
spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sampleText.setText(spannable);
} else {
sampleText.setText(fullText);
}
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});