7

在我的 android 应用程序中,我有一个包含特定单词的字符串,所以我想在文本视图中显示整个字符串,并且应该突出显示特定的单词。希望下面的图片能给你一个想法。

在此处输入图像描述

我已经使用以下代码来执行此操作,但它不起作用。

代码:

con 是我的字符串, groupNameContent 是文本字段。

con.replaceAll(arrGroupelements[groupPosition][5],"<font color='#CA278C'>"+arrGroupelements[groupPosition][5]+"</font>.");
groupNameContent.setText(Html.fromHtml(con));
4

3 回答 3

10

对于每个单词,您可以使用:

TextView textView = (TextView)findViewById(R.id.mytextview01);
//use a loop to change text color
Spannable WordtoSpan = new SpannableString("partial colored text");        
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(WordtoSpan);
于 2012-04-23T11:33:09.593 回答
4

如果我能理解你有单词列表,并且你想在文本中找到这个单词并突出显示它们,那么在这个答案中你有三个输入参数:

  1. 全文。
  2. 你的名单
  3. yourTextview 显示结果文本

    String text = "full of your text";
    Spannable textSpannable = new SpannableString(text);
    
    for (int j =0 ; j<yourList.size() ; j++) {
        //word of your list
        String word = String.valueOf(yourList.get(j));
        //find index of words
        for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
            //find the length of word for set color
            int last = i + word.length();
            //set text color with spannable
            textSpannable.setSpan(new BackgroundColorSpan(Color.parseColor("#0cab8f")),
                    i, last, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    yourTextView.setText(textSpannable);
    
于 2017-10-21T10:42:39.597 回答
-1

为了简单起见,我在这里发布我的方法

. . . . . . . .

首先准备使用方法

    ArrayList<String> searchWords = new ArrayList<String>(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);
    }

方法

    private Spannable setSpanHighlight(String text, @NonNull ArrayList<String> 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;
}
于 2020-07-22T12:17:45.500 回答