Выделите искомый текст в элементах ListView

enter image description here

У меня есть ListView, и я использую пользовательский адаптер для отображения данных. Теперь я хочу изменить цвет текстового текста, как показано на рисунке выше.

Вот код для SearchView

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.actionbar_menu_item, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    final SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
            .getActionView();
    searchView.setSearchableInfo(searchManager
            .getSearchableInfo(getComponentName()));
    searchView.setOnQueryTextListener(this);
        return super.onCreateOptionsMenu(menu);
        }

public boolean onQueryTextChange(String newText) {
    // this is adapter that will be filtered
      if (TextUtils.isEmpty(newText)){
            lvCustomList.clearTextFilter();
      }
      else{
            lvCustomList.setFilterText(newText.toString());
       }
    return false;
 }

@Override
public boolean onQueryTextSubmit(String query) {
    return false;
}

Спасибо.

Ответы

Ответ 1

Я предполагаю, что у вас есть пользовательский адаптер с getCount() и getView() реализован и уже фильтрует элементы, и вам просто нужна полужирная часть.

Для этого вам нужно использовать SpannableString, который в основном содержит текст с прикрепленной разметкой. Например, TextAppearanceSpan можно использовать для изменения шрифта, стиля шрифта, размера и цвета.

Итак, вы должны обновить свой адаптер getView(), чтобы изменить часть, в которой вы используете textView.setText(), в нечто более или менее похожее:

String filter = ...;
String itemValue = ...;

int startPos = itemValue.toLowerCase(Locale.US).indexOf(filter.toLowerCase(Locale.US));
int endPos = startPos + filter.length();

if (startPos != -1) // This should always be true, just a sanity check
{
    Spannable spannable = new SpannableString(itemValue);
    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);
    textView.setText(spannable);
}
else
    textView.setText(itemValue);

Ответ 2

Пример поиска Android Search [Нечувствительный к регистру порядок]

1. Простой поиск (Html): [Конкретное слово]

public static void setSearchTextHighlightSimpleHtml(TextView textView, String fullText, String searchText) {
    searchText = searchText.replace("'", "");
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            fullText = fullText.replaceAll("(?i)(" + searchText + ")", "<span style=\"background-color:#FCFF48;\"><b><big><font color='#a10901'>$1</font></big></b></span>");
            textView.setText(Html.fromHtml(fullText, Html.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE);
        } else {
            fullText = fullText.replaceAll("(?i)(" + searchText + ")", "<b><big><font color='red'>$1</font></big></b>");
            textView.setText(Html.fromHtml(fullText), TextView.BufferType.SPANNABLE);
        }
    } catch (Exception e) {
        textView.setText(fullText);
    }
}

2. Простой поиск (Spannable): [Конкретное слово]

public static void setSearchTextHighlightSimpleSpannable(TextView textView, String fullText, String searchText) {

    searchText = searchText.replace("'", "");

    // highlight search text
    if (null != searchText && !searchText.isEmpty()) {

        SpannableStringBuilder wordSpan = new SpannableStringBuilder(fullText);
        Pattern p = Pattern.compile(searchText, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(fullText);
        while (m.find()) {

            int wordStart = m.start();
            int wordEnd = m.end();

            // Now highlight based on the word boundaries
            ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

            wordSpan.setSpan(highlightSpan, wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            wordSpan.setSpan(new BackgroundColorSpan(0xFFFCFF48), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            wordSpan.setSpan(new RelativeSizeSpan(1.25f), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        textView.setText(wordSpan, TextView.BufferType.SPANNABLE);

    } else {
        textView.setText(fullText);
    }
}

3. Быстрый поиск (расширенный): [Полное слово]

public static void setAdvancedTitleHighlight(TextView textView, String fullText, String searchText) {

    searchText = searchText.replace("'", "");

    final String WORD_SINGLE = " ";

    // highlight search text
    if (null != searchText && !searchText.isEmpty() && !searchText.equals(WORD_SINGLE)) {

        SpannableStringBuilder wordSpan = new SpannableStringBuilder(fullText);
        Pattern p = Pattern.compile(searchText, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(fullText);
        while (m.find()) {

            final char WORD_BOUNDARY = ' ';

            int wordStart = m.start();
            while (wordStart >= 0 && fullText.charAt(wordStart) != WORD_BOUNDARY) {
                --wordStart;
            }
            wordStart = wordStart + 1;

            int wordEnd = m.end();
            while (wordEnd < fullText.length() && fullText.charAt(wordEnd) != WORD_BOUNDARY) {
                ++wordEnd;
            }

            // Now highlight based on the word boundaries
            ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

            wordSpan.setSpan(highlightSpan, wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            wordSpan.setSpan(new BackgroundColorSpan(0xFFFCFF48), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            wordSpan.setSpan(new RelativeSizeSpan(1.25f), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        textView.setText(wordSpan, TextView.BufferType.SPANNABLE);

    } else {
        textView.setText(fullText);
    }
}

4. Подробный поиск (расширенный): [Full Word]

public static void setAdvancedDetailsHighlight(TextView textView, String fullText, String searchText) {

    searchText = searchText.replace("'", "");

    final String WORD_SINGLE = " ";
    final String WORD_SINGLE1 = "\n";
    final String WORD_SINGLE2 = "(";
    final String WORD_SINGLE3 = ")";
    final String WORD_SINGLE4 = "।";
    final String WORD_SINGLE5 = ".";
    final String WORD_SINGLE6 = ",";
    final String WORD_SINGLE7 = ";";
    final String WORD_SINGLE8 = "?";
    final String WORD_SINGLE9 = "-";
    final String WORD_SINGLE10 = "+";

    // highlight search text
    if (null != searchText && !searchText.isEmpty() && !searchText.equals(WORD_SINGLE) && !searchText.equals(WORD_SINGLE1) && !searchText.equals(WORD_SINGLE2)
            && !searchText.equals(WORD_SINGLE3) && !searchText.equals(WORD_SINGLE4) && !searchText.equals(WORD_SINGLE5)
            && !searchText.equals(WORD_SINGLE6) && !searchText.equals(WORD_SINGLE7) && !searchText.equals(WORD_SINGLE8)
            && !searchText.equals(WORD_SINGLE9) && !searchText.equals(WORD_SINGLE10)) {

        SpannableStringBuilder wordSpan = new SpannableStringBuilder(fullText);
        Pattern p = Pattern.compile(searchText, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(fullText);
        while (m.find()) {

            final char WORD_BOUNDARY = ' ';
            final char WORD_BOUNDARY1 = '\n';
            final char WORD_BOUNDARY2 = '(';
            final char WORD_BOUNDARY3 = ')';
            final char WORD_BOUNDARY4 = '।';
            final char WORD_BOUNDARY5 = '.';
            final char WORD_BOUNDARY6 = ',';
            final char WORD_BOUNDARY7 = ';';
            final char WORD_BOUNDARY8 = '?';
            final char WORD_BOUNDARY9 = '-';

            int wordStart = m.start();
            while (wordStart >= 0 && fullText.charAt(wordStart) != WORD_BOUNDARY
                    && fullText.charAt(wordStart) != WORD_BOUNDARY1
                    && fullText.charAt(wordStart) != WORD_BOUNDARY2
                    && fullText.charAt(wordStart) != WORD_BOUNDARY3
                    && fullText.charAt(wordStart) != WORD_BOUNDARY4
                    && fullText.charAt(wordStart) != WORD_BOUNDARY5
                    && fullText.charAt(wordStart) != WORD_BOUNDARY6
                    && fullText.charAt(wordStart) != WORD_BOUNDARY7
                    && fullText.charAt(wordStart) != WORD_BOUNDARY8
                    && fullText.charAt(wordStart) != WORD_BOUNDARY9) {
                --wordStart;
            }
            wordStart = wordStart + 1;

            int wordEnd = m.end();
            while (wordEnd < fullText.length() && fullText.charAt(wordEnd) != WORD_BOUNDARY
                    && fullText.charAt(wordEnd) != WORD_BOUNDARY1
                    && fullText.charAt(wordEnd) != WORD_BOUNDARY2
                    && fullText.charAt(wordEnd) != WORD_BOUNDARY3
                    && fullText.charAt(wordEnd) != WORD_BOUNDARY4
                    && fullText.charAt(wordEnd) != WORD_BOUNDARY5
                    && fullText.charAt(wordEnd) != WORD_BOUNDARY6
                    && fullText.charAt(wordEnd) != WORD_BOUNDARY7
                    && fullText.charAt(wordEnd) != WORD_BOUNDARY8
                    && fullText.charAt(wordEnd) != WORD_BOUNDARY9) {
                ++wordEnd;
            }

            // Now highlight based on the word boundaries
            ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

            wordSpan.setSpan(highlightSpan, wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            wordSpan.setSpan(new BackgroundColorSpan(0xFFFCFF48), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            wordSpan.setSpan(new RelativeSizeSpan(1.25f), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        textView.setText(wordSpan, TextView.BufferType.SPANNABLE);

    } else {
        textView.setText(fullText);
    }
}

Если вы используете какой-либо из этих методов, ваша проблема будет решена... IngShaaAllah.