简体   繁体   中英

Changing string resourses programmatically in android

So i am making an app which has a lot of string.
And what i am trying to make the same layout open just with different strings(the string fill the layout).
So i have strings called opna0,opna1,opna2... and up. When you press a button to access the string a number is passed to the class handling the layout and i want the class to take that number, add it to opna and get that recourse.
So if i press button number 3 i want the textview to get the resourse

        "@strings/opna3"

but i have no idea how to do that so i was wondering if anyone got the answer?

the simplest thing you can do is:

int stringId = getResources().getIdentifier("opna"+value, "string", getPackageName());
if (stringId > 0) {
  yourTextView.setText(stringId);
}

getIdentifier() returns a resource identifier for the given resource name.

Use string array like this. load using resource

 <string-array name="array_items">
    <item name="item1">ONE</item>
    <item name="item2">TWO</item>
    <item name="item3">THREE</item>
</string-array>

load the strings and set the text depends on the click/index

String[] items = getResources().getStringArray(R.array.array_items);

You're looking for this: Resources getIdentifier

you can see an example from a previous question like yours: Android, getting resource ID from string?

One option would be to choose the string at runtime by storing the resource id in a Map<Integer, Integer> . Something like the following:

private Map<Integer, Integer> mStringMap;
{
    mStringMap.put(0, R.string.opna0);
    mStringMap.put(1, R.string.opna1);
    mStringMap.put(2, R.string.opna2);
    mStringMap.put(3, R.string.opna3);
    ...
}

private void setStringFromResource(int id){
    if(mStringMap.containsKey(id)) mTextView.setText(mStringMap.get(id));
}

When a button is pressed, pass the corresponding integer value to setStringFromResource() . This method find the correct resource in mStringMap and then sets your TextView 's text to that resource. You won't be setting the string for your TextView in the layout xml, but rather at runtime programmatically.

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