gpt4 book ai didi

java - (Android) 更改 strings.xml 中的文本颜色

转载 作者:行者123 更新时间:2023-11-29 03:07:20 24 4
gpt4 key购买 nike

首先,根据用户的操作,我想从我的 strings.xml 资源文件中检索特定的字符串:

String option1 = context.getString(R.string.string_one)
String option2 = context.getString(R.string.string_two)
String option3 = context.getString(R.string.string_three)

然后,我将这些字符串作为 String[] options 传递定制adapter对于 ListView我在哪里设置 TextView 的文本

    public ChoicesAdapter(Context context, String[] options) {
super(context, R.layout.choice_option_layout_2,choices);
}



@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater MyInflater = LayoutInflater.from(getContext());
View MyView = MyInflater.inflate(R.layout.option_list_layout, parent, false);

String option = getItem(position);
TextView textView = (TextView) MyView.findViewById(R.id.textView);

textView.setText(Html.fromHtml(option));

return MyView;
}

我希望我的 strings.xml 文件中的不同字符串具有不同的颜色或不同的格式。例如,这是我的一个字符串:

 <string name ="exit"><![CDATA[<i>exit</i>]]></string>

但是,当这个字符串显示在屏幕上时,它显示为:"<i>exit</i>"

因此,我猜测我的方法中某处丢失了 string.xml 资源的格式。我怎样才能得到它而不是显示 "<i>exit</i>" ,它会在屏幕上显示“退出”吗?

我想我的问题是我在哪里使用 .getString() .这是否以某种方式忽略了我在 .xml 文件中添加的格式?

最佳答案

查看 http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling - 他们的例子是:

<string name="welcome">Welcome to <b>Android</b>!</string>

它说你可以使用 <b>text</b>对于粗体 文本,<i>text</i>对于 斜体 文本,和 <u>text</u>用于带下划线的文本。

其中的重要部分是,“通常情况下,这是行不通的,因为 String.format(String, Object...) 方法将从字符串中去除所有样式信息。解决方法是编写带有转义实体的 HTML 标签,然后在格式化后用 fromHtml(String) 恢复。”

他们说“将您的样式化文本资源存储为 HTML 转义字符串”,例如

 <string name="exit">&lt;i>exit&lt;/i></string>

然后使用:

Resources res = getResources();
String text = String.format(res.getString(R.string.exit));
CharSequence styledText = Html.fromHtml(text);

正确获取格式化的文本。

关于java - (Android) 更改 strings.xml 中的文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31480379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com