【问题标题】:Android change color part of a stringAndroid更改字符串的颜色部分
【发布时间】:2016-05-03 15:05:27
【问题描述】:

我有一个字符串名称“classe”。它包含许多单词和短语。但是当字符串包含单词"idiom"时,我想改变颜色。我以编程方式做到了,但它改变了所有字符串“classe”的颜色。我只想改变“成语”的颜色(单词的一部分,而不是整个短语)。我怎样才能以编程方式做到这一点?

    if (classe.contains("idiom")) {

        txtclasse.setTextColor(getResources().getColor(R.color.orange));
    }

【问题讨论】:

标签: android textview


【解决方案1】:

使用 ForegroundColorSpan。

if(classe != null && classe.contains(“idiom”))
{
    Spannable spannable = new SpannableString(classe);
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), classe.indexOf(“idiom”), classe.indexOf(“idiom”) + “idiom”.length(),     Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    txtclasse.setText(spannable);
}

【讨论】:

    【解决方案2】:

    你可以用 HTML 来解决它。

    origString = txtclasse.getText().toString();
    origString = origString.replaceAll("idiom","<font color='red'>idiom</font>");
    
    txtclasse.setText(Html.fromHtml(origString));
    

    【讨论】:

    • 没用!整个字符串短语在屏幕上是空的:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    相关资源
    最近更新 更多