在字符串中设置文本颜色启动min SDK版本7

时间:2013-11-15 08:43:57

标签: android colors textview

我的代码中有这一行。

String credit= "<font color='#0166b9'>Credit: </font>";

我需要从我的资源中获取“Credit:”字符串,因为它可以更改依赖于设备默认语言。那我怎么能在这一行中使用某些变量的值呢?

修改

我必须只有一个单词或一些文字。这意味着我必须有不同颜色的TextView。

有一些方法可以在R.strings中设置颜色,这是示例

<string name="clients_credit"> <font fgcolor="#0166b9">Credit: </font> </string>

但它仅适用于最新版本。因此,找到一些在string.xml中设置颜色的方法会很棒。

5 个答案:

答案 0 :(得分:1)

使用可以使用Html.fromHtml();

您可以在string.xml中将字符串定义为

<string name="title"><![CDATA[<font color='#0166b9'>Credit: </font>]]></string>

在java文件中,您需要使用spannable text

textView.setText(Html.fromHtml(getResources.getString(R.string.title)), TextView.BufferType.SPANNABLE);

答案 1 :(得分:0)

将信用额添加到您的strings文件中,然后稍后检索getResources().getString(R.string.credit),并添加getResources().getColor(R.color.textColour)之类的颜色。添加

<color name="textColor">#0166b9</color>

color文件夹中的res XML。如果你没有创建一个。

答案 2 :(得分:0)

你可以这样做:

Textview tV;
// Initialize textview 
tV.setText(R.string.credit);
tV.setBackgroundResource(R.color.background_color);
tV.setTextColor(getResources.getColor(R.color.text_color));

答案 3 :(得分:0)

将名为colors.xml的文件放在Android项目的res / values下。

声明该文件中的颜色

<color name="myColor">#ff0166b9<color>

在res / values

下的strings.xml中声明字符串
<string name="credit">"Credit: "</string>

在您的Activity中,使用

获取对活动布局中定义的TextView的引用
textView = (TextView) findViewById(R.id.idOfTextView);

然后使用以下内容设置字符串和文本颜色。

textView.setText(R.string.credit);
textView.setTextColor(getResources().getColor(R.color.myColor));

希望这有帮助。

答案 4 :(得分:0)

我找到了解决方案。就是这样。

TextView debitTxtView = (TextView) view.findViewById(R.id.txtViewclientDebit);
final Spannable clientsDebit= new SpannableString(mContext.getString(R.string.clients_debit));
clientsDebit.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.blue)), 0, clientsDebit.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
debitTxtView.setText(clientsDebit);
debitTxtView.append(" " + file.getDebit());