简体   繁体   中英

Android string resource with a number

Im having an issue when using getIdentifier(resourceName, "string", packageName) . My string resources name is dynamic and is combined of a prefix, which is "number_" and a postfix, which is a number eg "5". The final string name looks like this "number_5". The problem is when im using the getIdentifier method it still returns a resId, as if this resource would exists in my locale, but i don't have it in my current locale, it's in another one.

I've tried to clean my project and i tried to use getIdentifier(packageName + ":string/" + resourceName, null, null)) and also

public static int getResId(String variableName, Class<?> c) {
    try {
        Field idField = c.getDeclaredField(variableName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

The context of current locale is correct, i've checked it by:

c.getResources().getConfiguration().locale

Why does getIdentifier return a valid resource id from another non-default string resources?

It returns a valid identifier because there is one: your R class contains the identifier. How this identifier is resolved when you load the resource is a completely different matter. Please note that you should always provide all the strings in the default folder ( res/values ) to avoid runtime errors.

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