Note that there are some explanatory texts on larger screens.

plurals
  1. POPrefixing string resource identifier to select alternate version at run time
    text
    copied!<p>Normally, I fetch a string value from a resource XML using:</p> <pre><code>String mystring = getResources().getString(R.string.mystring); </code></pre> <p>Now, I would like to select an alternate version of the string based on some runtime condition.</p> <pre><code>String selectivestring; if (someBooleanCondition) selectivestring= getResources().getString(R.string.mystring); else selectivestring= getResources().getString(R.string.theirstring); </code></pre> <p>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_"):</p> <pre><code>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); </code></pre> <p>(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)</p> <p>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?</p> <p><strong>Note:</strong> The alternate version of each string is <a href="https://stackoverflow.com/questions/12072134/get-string-from-different-values-folder-in-android">not</a> 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. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload