0
文字列fullText = "私たちの名誉ある首相";Android Searchハイライトフルワード
文字列searchText = "onor";
「onor」というテキストをハイライトすることができます。
[下のコードを使用して]しかし、私は「名誉」テキスト私の検索文字列がある「onor」フルハイライトします。
私のコードは次のとおりです。
public static void setSearchText(TextView textView, String fullText, String searchText) {
// highlight search text
if (null != searchText && !searchText.isEmpty()) {
int startPos = fullText.indexOf(searchText);
int endPos = startPos + searchText.length();
if (startPos != -1) {
int ofe = fullText.indexOf(searchText, 0);
Spannable WordtoSpan = new SpannableString(fullText);
for (int ofs = 0; ofs < fullText.length() && ofe != -1; ofs = ofe + 1) {
ofe = fullText.indexOf(searchText, ofs);
if (ofe == -1)
break;
else {
ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.RED});
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);
WordtoSpan.setSpan(highlightSpan, ofe, ofe + searchText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
WordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe + searchText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
WordtoSpan.setSpan(new RelativeSizeSpan(1.5f), ofe, ofe + searchText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
}
}
} else {
textView.setText(fullText);
}
} else {
textView.setText(fullText);
}
}
を、あなたは「外側」から「単語」の境界を検索し、その文字の範囲を強調表示する必要があります。 –
'java.text.BreakIterator'を使う – pskink
あなたは' BreakIterator'ドキュメントにたくさんの例を持っています – pskink