简体   繁体   中英

Is it possible to change a String value into a R.string reference name?

The title is a little confusing so let me explain further. An application I am trying to make has multiple buttons opening a new activity that look the same, but the text is different depending on the button clicked (Like a dictionary). So instead of recreating the activity 50+ times, I made a new method for onClick() in the first activity with a new Intent, and added a getIntent() to the second activity.

//first activity method
public final static String TRANSFER_SYMBOL = "com.engineering.dictionary.MESSAGE";

public void openView(View view)
{
  Intent open = new Intent(this,displayCharHB.class);
  Button setBtn = (Button) findViewById(view.getId());
  String grabText = setBtn.getText().toString();
  String thisChar = "sym_hira_" + grabText;
  open.putExtra(TRANSFER_SYMBOL,thisChar);
  startActivity(open);
}


//second Activity method
@Override
protected void onCreate(Bundle savedInstanceState) {
    Intent grabChar = getIntent();
    String thisChar = grabChar.getStringExtra(hira_basic.TRANSFER_SYMBOL);
    //String strValue = "R.string." + thisChar;


    TextView displaySym = (TextView) findViewById(R.id.charDisplay);
    displaySym.setText(thisChar);
}

sym_hira_ + whatever is stored in grabText is the name of a String in strings.xml (For example, grabText = "ro", sym_hira_ro is a String name). Is it possible to get it to reference that string name with setText() and not actually set the text to "sym_hira_..."?

Is it possible to get it to reference that string name with setText()

Use getIdentifier to get value from strings.xml using name:

int resId = getResources().getIdentifier(thisChar, "string",getPackageName());
displaySym.setText(getResources().getString(resId));

you can using BeanShell execute the "R.string.xxxx" command to get the string resource id.

this is my code example;

String str = "";
Interpreter i = new Interpreter();
i.set("context", MainActivity.this);
Object res = i.eval("com.example.testucmbilebase.R.string.hello_world");
if(res != null) {
    Integer resI = (Integer)res;
    str = MainActivity.this.getResources().getString(resI);
} 

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