简体   繁体   中英

Dynamically add values to resource string-array in Android

Is there a way to dynamically add values to an Android resource string-array ?

Eg:

    <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="titles">
    </string-array>
</resources>

Is there a way to dynamically add values to an Android resource string-array?

No, because resources are read-only at runtime.

Yes! you can create a static array of strings in Android but dynamically adding values to an Android resource is not yet possible. It turns out that it's easy to create and use a static array of strings in Android. Of course, you can do this in Java code, as I describe in my Java string array tutorial, but for Android, I'm talking about doing this in XML.

In short, this is how you define a static string array in an Android XML file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="my_books">
        <item>Scala Cookbook</item>
        <item>Play Framework Recipes</item>
        <item>How I Sold My Business: A Personal Diary</item>
        <item>A Survival Guide for New Consultants</item>
    </string-array>
</resources>

Then inside an Activity, Fragment, or other Java class, you can create a string array in Java from that XML like this:

Resources res = getResources();
String[] myBooks = res.getStringArray(R.array.my_books);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM