Issue
I have a const's in my class that saves the keys of values:
public static final String CAR_NAME = "car_name";
public static final String CAR_NUMBER = "car_number";
values.xml
<string name="car_name">Tl5t</string>
<string name="car_name_tr">Tl5tTR</string>
<string name="car_number">45334234</string>
and a method that return the right resource id:
public void returnResourceId (String resource) {
if (state == 1){
resource = resource+"_tr";
}
return Resources.getSystem().getIdentifier(resource, "string",getPackageName() );
}
I'm using the method like this:
int resourceId = returnResourceId(CAR_NAME);
The problem is that I need to manage twice the resource name, one time in the class const's and one time in the values.xml file.
Can I somehow keep working with my logic but using only one key?
Solution
I would recommend that you don't do this, as it will be much slower than direct access. That said, you can do this by looking up the name of the resource, appending your suffix, and then looking up the resource ID of the extra string with the _tr suffix.
For example:
@StringRes
public int getResourceId(@StringRes int baseResourceId) {
// Assume baseResourceId == R.string.car_name
if (state == 1) {
final Resources res = getResources();
// Will return "car_name"
final String resourceName = res.getResourceEntryName(baseResourceId);
// Look up and return the integer ID for "car_name_tr"
return res.getIdentifier(resourceName + "_tr", "string", BuildConfig.APPLICATION_ID);
} else {
// Otherwise just return the input
return baseResourceId;
}
}
Answered By - Kevin Coppock
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.