【问题标题】:How to display highlight string in textView in android?如何在android的textView中显示高亮字符串?
【发布时间】:2018-01-23 17:20:58
【问题描述】:
我正在构建一个 android 应用程序,我在其中解析一组数据并显示在 listView 中。现在,当用户在该数据集中搜索一个词时,我会突出显示该文本视图的词。
现在的问题是,当该搜索词开始时,它显示为文本视图最大第 1 行,但如果它是段落中间词的最后一个被突出显示,但我想在文本视图中显示该突出显示的词最大线 1。
有什么方法可以调整文本视图中的字符串并显示突出显示的区域。
【问题讨论】:
标签:
android
string
listview
textview
【解决方案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);
【解决方案2】:
我已经在片段中进行了尝试。希望这会对你有所帮助。
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) {
}
});