Issue
Normally, I fetch a string value from a resource XML using:
String mystring = getResources().getString(R.string.mystring);
Now, I would like to select an alternate version of the string based on some runtime condition.
String selectivestring;
if (someBooleanCondition)
selectivestring= getResources().getString(R.string.mystring);
else
selectivestring= getResources().getString(R.string.theirstring);
So far so good, but since I have many such "alternative string pairs", I would like to methodically prefix one type (say, "my_") and the alternate type (say, "alt_"):
String selectivestring1;
if (someBooleanCondition)
selectivestring1= getResources().getString(R.string.my_string1);
else
selectivestring1= getResources().getString(R.string.alt_string1);
.
.
.
String selectivestring2;
if (someBooleanCondition)
selectivestring2= getResources().getString(R.string.my_string2);
else
selectivestring2= getResources().getString(R.string.alt_string2);
(The above code is for illustration only. What I eventually want to do is to parametrize this so that I can put this in a loop, array or own accessor)
If there were a preprocessor in Java, I could have just used string concatenation to select "my_" vs. "alt_" prefix. But since I know there isn't, is there a way, workaround or suggestion to modify the string resource identifier at runtime, as outlined above?
Note: The alternate version of each string is not in a different language/locale. I am basically trying to keep the original and the alternate versions of the string together, next to each other, in the same resource file, so that I can easily compare the two.
Solution
Firstly, your code could be a bit better like this:
int resource =
someBooleanCondition ?
R.string.my_string2 : R.string.alt_string2;
String selectivestring2 = getResources().getString(resource);
As you described, that could be done with reflection, here is a very simple example:
package br;
import java.lang.reflect.Field;
final class R {
public static final class string {
public static final int alt_string1=0x7f060601;
public static final int alt_string2=0x7f060101;
}
}
public class StaticReflection {
public static boolean globalVariable = false;
//this would be android method getString
public static String fakeGetString(int id){
switch (id){
case R.string.alt_string1: return "it";
case R.string.alt_string2: return "works";
default:
return "O NOES";
}
}
//static method
public static String getResource(String resId) throws Exception {
if (globalVariable){
resId += "string1";
} else {
resId += "string2";
}
Field f = R.string.class.getDeclaredField(resId);
Integer id = (Integer) f.get(null);
return fakeGetString(id);
}
public static void main(String[] args) throws Exception {
globalVariable=true;
System.out.println(getResource("alt_"));
globalVariable=false;
System.out.println(getResource("alt_"));
}
}
Answered By - mrcaramori
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.