Issue
First, depending on the user's actions, I want to retrieve a certain strings from my strings.xml resource file:
String option1 = context.getString(R.string.string_one)
String option2 = context.getString(R.string.string_two)
String option3 = context.getString(R.string.string_three)
Then, I pass these strings as String[] options
to a custom adapter
for a ListView
where I set the text of a 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;
}
I want different strings in my strings.xml file to have different colors or different formatting. For example, here is one of my strings:
<string name ="exit"><![CDATA[<i>exit</i>]]></string>
However, when this string is displayed on the screen, it shows as: "<i>exit</i>"
So, I'm guessing somewhere in my method I am losing the string.xml resource's formatting. How can I get it so instead of showing "<i>exit</i>"
, it will show "exit" on the screen?
I am thinking my problem is where i use .getString()
. Is this somehow ignoring the formatting that I added to it in the .xml file?
Solution
Check out http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling - their example is:
<string name="welcome">Welcome to <b>Android</b>!</string>
It says you can use <b>text</b>
for bold text, <i>text</i>
for italic text, and <u>text</u>
for underlined text.
The important part of this is, "Normally, this won't work because the String.format(String, Object...)
method will strip all the style information from the string. The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String)
, after the formatting takes place."
They say to "store your styled text resource as an HTML-escaped string" like
<string name="exit"><i>exit</i></string>
and then use:
Resources res = getResources();
String text = String.format(res.getString(R.string.exit));
CharSequence styledText = Html.fromHtml(text);
to get the formatted text correctly.
Answered By - WOUNDEDStevenJones
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.