簡體   English   中英

更改資源字符串中的單詞顏色

[英]Change word color in resource string

反正有沒有在android中設置字符串資源的顏色? 我的意思是,我知道我可以使用一些html標簽來改變字符串樣式(或子字符串),但沒有發現任何改變顏色。 我在stackoverflow中看到過其他解決方案,比如在設置文本之前將字符串傳遞給Html.fromHtml(字符串),但我想在字符串資源編輯器中執行此操作。 有可能嗎?

看起來這個方法有效:

    <string name="some_text">this is <font fgcolor="#ffff0000">red</font></string>

據我所知,這是不可能的。 我會使用SpannableString來改變顏色。

    int colorBlue = getResources().getColor(R.color.blue);
    String text = getString(R.string.text);
    SpannableString spannable = new SpannableString(text);
    // here we set the color
    spannable.setSpan(new ForegroundColorSpan(colorBlue), 0, text.length(), 0);

Spannable非常好。 您可以將think設置為fontseize和stuff,並將其附加到文本視圖中。 優點是您可以在一個視圖中使用不同的顏色。

編輯:好的,如果你只想設置上面提到的解決方案的顏色我就是你要走的路。

我最近為這個問題提出了一個靈活的解決方案。 它使我能夠通過使用方法鏈輕松地向子串添加多個樣式。 它使用了SpannableString。 如果要為某個子字符串指定顏色,可以使用ForegroundColorSpan。

public StyledString putColor(String subString, @ColorRes int colorRes){
    if(getStartEnd(subString)){
        int color = ColorUtil.getColor(context, colorRes);
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(color);
        fullStringBuilder.setSpan(foregroundColorSpan, startingIndex, endingIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    return this;
}

有關完整代碼,請參閱要點

字符串本身沒有顏色,但您可以更改它們出現的textView中的文本顏色。請參閱textview文檔 ,但有兩種方法可以執行此操作。

XML

android:textColor

setTextColor(int)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM