2017-06-07 32 views
0

我试图以编程方式添加一个快捷方式文本的多个html前景格式。Snackbar中的多格式html格式

在我的strings.xml:

<string name="html_test">The html entries %1$s and %2$s are looking different.</string> 

我如何努力进行格式化:

public static Spanned getString(Context p_Context, int p_iResID, int p_iColor, String... p_Items) { 
    int l_iColor = ContextCompat.getColor(p_Context, p_iColor); 
    String l_HexColor = Integer.toHexString(l_iColor); 

    String l_Before = "&lt;font color=" + l_HexColor + ">"; 
    String l_After = "&lt;/font>"; 

    Object[] l_Items = new String[p_Items.length]; 
    for(int i = 0; i < p_Items.length; i++) { 
     l_Items[i] = l_Before + p_Items[i] + l_After; 
    } 

    return Html.fromHtml(p_Context.getString(p_iResID, l_Items)); 
    } 

我如何调用该函数:

getString(getContext(), R.string.html_test, R.color.blue, "Test1", "Test2"); 

然后,我创建的小吃店和传递html格式的文本。

Snackbar l_SnackBar = Snackbar.make(p_Root, p_Text, p_iSnackBarLenght); 
l_SnackBar.getView().setBackgroundColor(p_iBGColor); 
return l_SnackBar; 

问题是没有html格式的我输入getString()的两个条目。

我不想使用![CDATA...,因为我读到格式化存在一些问题。

回答

0

我没有找到一个解决方案,用html格式化getString()的前景参数。现在即时通过SpannableString这对我有用。我的代码现在看起来像这样:

public static SpannableString getString(Context p_Context, int p_iResID, int p_iColor, Object... p_Items) { 
    String l_Feedback = p_Context.getString(p_iResID, p_Items); 
    SpannableString l_SpannableFeedback = new SpannableString(l_Feedback); 
    int l_iItemColor = ContextCompat.getColor(p_Context, p_iColor); 

    for(Object l_Object : p_Items) { 
     String l_Item = (String) l_Object; 
     int l_iStartIndex = l_Feedback.indexOf(l_Item); 
     int l_iEndIndex = l_iStartIndex + l_Item.length(); 

     l_SpannableFeedback.setSpan(new ForegroundColorSpan(l_iItemColor), l_iStartIndex, l_iEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
     l_SpannableFeedback.setSpan(new StyleSpan(Typeface.BOLD), l_iStartIndex, l_iEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
    } 

    return l_SpannableFeedback; 
    }