简体   繁体   中英

Is it possible to replace the name at the end of the R.string. call with a variable

Hie sorry, noob here so dont really know termology. What i want to do is replace the end of a command like this

((TextView) findViewById(R.id.rr)).setText(R.string.Constitution);

to something more dynamic, substituting the word Constitution, which is a reference to a string in the strings.xml resource, with a variable. This is the way i thought would work, but it isant

    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    String textFromSpinner = spinner.getSelectedItem().toString();

    if (textFromSpinner.contains(" ")){
        textFromSpinner = textFromSpinner.replaceAll(" ", "_");
    }

    String valueToGet = "R.string" + textFromSpinner;

    ((TextView) findViewById(R.id.rr)).setText(valueToGet);

}

that refused, I also tried a number of variations that were rejected immediately by Android Studio which showed me red lines.

Please help, and also, please be kind in as i am still learning how to code so i am not knowlegebale

You can call getResource().getIdentifier() method to retrieve a resource by its name at runtime. Check this: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29

int stringId = context.getResources().getIdentifier(textFromSpinner, "string", context.getPackageName());

With this line you can get the id of your desired string resource. Then you can pass it to your TextView :

((TextView) findViewById(R.id.rr)).setText(stringId);
<string name="hello_world">Hello %1$s</string>

Replace @runtime

String str = "World";
str = String.format(getResources().getString(R.string.hello_world), str );
 int searchId = getResources().getIdentifier(textFromSpinner, "string", this.getPackageName());
    if (searchId != 0){
        ((TextView) findViewById(R.id.rr)).setText(searchId);
    } else {
        ((TextView) findViewById(R.id.rr)).setText(R.string.Please_Select_Option);
    }

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