首页 > 解决方案 > 如何使用 html 突出显示某些文本?

问题描述

工作完美,但是当我使用 html 突出显示文本时,某些文本无法完美查看(印地语文本)。

安卓

String str="रिश्ते भले ही कम ही बनाओ लेकिन दिल से निभाओ,\n" +
                "क्योंकि आज कल इंसान अच्छाई के चक्कर में अच्छे खो देते है।";


//textview.setText(str);
textview.setText(Html.fromHtml(String.format(colorfulltext(str))), TextView.BufferType.SPANNABLE);      


// highlight text
public String colorfulltext(String text) {
    String[] colors = new String[]{"#fdc113", "#fdc113", "#fdc113","#fdc113", "#fdc113" ,"#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc","#fcfcfc","#fcfcfc","#fcfcfc","#fcfcfc"};

    StringBuilder finals = new StringBuilder();

    int size = colors.length;
    int k = 0;
    for (int item = 0; item < text.length(); item++) {
        if (k >= size) {
            k = 0;
        }
        finals.append("<font color='" + colors[k] + "'>" + text.charAt(item) + "</font>");
            k++;
    }
    return finals.toString();
}

屏幕

标签: android

解决方案


为什么要将 String 转换为 html 以将 fontcolor 应用于静态文本?

您必须按照以下步骤操作:

  1. 在 Strings.xml 中为每个文本创建条目。例如,रिश्ते 有不同的颜色,需要在 strings.xml 中作为单独的条目。
  2. 将此添加到 Util 类:

    public static void addColoredPart(SpannableStringBuilder ssb,
                                   String word, int color,String... texts) {
    
    for(String text : texts) {
        if (word != null) {
            int idx1 = text.indexOf(word);
            if (idx1 == -1) {
                return;
            }
            int idx2 = idx1 + word.length();
            ssb.setSpan(new ForegroundColorSpan(color), idx1, idx2, 
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
     }
    }
    
  3. 通过以下方式应用样式:

    String string1 = context.getString(R.string.String_id1)
    String string2 = context.getString(R.string.String_id2)
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
    spannableStringBuilder.append(string2)
    spannableStringBuilder.append(string2)
    SpannableUtil.addColoredPart(
                        spannableStringBuilder,
    spannableStringBuilder.toString(), color, string1, string2);
    

推荐阅读