How to search for a word in a string and highlight word in a text view in android?

前端 未结 3 792
广开言路
广开言路 2020-12-30 12:46

in my android application i have a string that contains a specific word so i want to display whole string in text view and the specific word should be highlighted.Hope follo

3条回答
  •  离开以前
    2020-12-30 13:14

    Just to make it simple, here I post my methode

    . . . . . . . .

    First getting ready to use the methode

        ArrayList searchWords = new ArrayList(Arrays.asList("Second", "Scottish", "forces", "England"));
    
        String text = "1333 – Second War of Scottish Independence: The Scottish-held town of Berwick-upon-Tweed surrendered to English forces, ending a siege led by Edward III of England (depicted).";
    
    
        TextView sampleTextView = new TextView(currentContext); // currentContext = getContext();
    
        if (searchWords != null) {
            Spannable newText = setSpanHighlight(text, searchWords);
            sampleTextView.setText(newText, TextView.BufferType.SPANNABLE);
        }
        else{
            sampleTextView.setText(text);
        }
    

    The methode

        private Spannable setSpanHighlight(String text, @NonNull ArrayList searchWord) {
        Spannable newText = new SpannableString(text);
    
        if (searchWord.size() != 0) {
            for (String word : searchWord){
                if (text.contains(word)){
                    int beginIndex = text.indexOf(String.valueOf(word)); //Unnecessary 'String.valueOf()' call => if you have something else than String
                    int endIndex = beginIndex + word.length();
    
                    newText.setSpan(
                            new ForegroundColorSpan(Color.BLUE),
                            beginIndex,
                            endIndex,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        }
        return newText;
    }
    

提交回复
热议问题