Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add resource-strings to Char Sequence

Tags:

android

I have the following problem:

I created a Char Sequence and was able to name 4 units. I would however rather use strings from my XML file for localization purposes. Is there any way to achieve that?

final CharSequence[] choices = 

        //want to add strings here i.e. R.strings.lemonade  
        {"Coke", "Pepsi" , "Sprite" , "Seven Up" };

builderType.setSingleChoiceItems( choices, selected, new OnClickListener()
                    {.......

Error message:

Type mismatch: cannot convert from int to CharSequence

like image 323
momo Avatar asked Apr 26 '13 10:04

momo


2 Answers

There's another overload of AlertDialog.Builder.setSingleChoiceItems() that takes in an int resource id for a string array of items. Put the following in an xml in res/values e.g. strings.xml:

<string-array name="choices">
    <item>Coke</item>
    <item>Pepsi</item>
    <item>Sprite</item>
    <item>Seven Up</item>
</string-array>

Then you can use it as:

builderType.setSingleChoiceItems(R.array.choices, selected, new OnClickListener(), ...

For generic cases, you can also load string array resources with Resources.getStringArray() as suggested by @Egor.

like image 61
laalto Avatar answered Oct 17 '22 22:10

laalto


Create a string-array in strings.xml

<string-array name="choices">
    <item>Coke</item>
    <item>Pepsi</item>
    <item>Sprite</item>
    <item>Seven Up</item>
</string-array>

Then fetch it from resources

String[] choices = context.getResources().getStringArray(R.array.choices);

Then use it in setSingleChoiceItems() as is, since String implements CharSequence.

like image 34
Egor Avatar answered Oct 17 '22 23:10

Egor