Creating Strings than can be used as Filepath - Eclipse / Android

孤人 提交于 2019-12-11 11:04:28

问题


More Code - The String Created here is R.string.c#### - c.#### is a pre-defined string i want to run as a setText.

int Q1 = question1.getmCounter();
int Q2 = question2.getmCounter();
int Q3 = question3.getmCounter();
int Q4 = question4.getmCounter();

int qTotal = Q1 + Q2 + Q3 + Q4;
String Test5 = "R.string.c" + qTotal;

This is how i am now getting the "string" i want to feed.

    textOut = (TextView) findViewById(R.id.ChmpNametxt);
    textOut.setText(Test5);

This is where i want to feed it.


回答1:


You can access to resources by using the "getIdentifier" method. It allows to access any resource of the package:

getResources().getIdentifier("c1123", "string", this.class.getPackageName());

You can pass any variable in the first argument, this corresponds to the name of your string. The second argument specifies in which resources to search it (string, drawable, layout.....). The third argument is the application's package name. It specifies which "R" is used. In your case, you want to look inside the resources ("R") contained in your application.

Edit: This method returns an int, that correspond to the ID of the resource you're looking for, for exemple R.string.c1123

Edit2: This int should then be used as the parameter for the setText function.

So the complete code would be:

int resId = getResources().getIdentifier("c" + qTotal, "string", this.class.getPackageName());
textOut.setText(resId);


来源:https://stackoverflow.com/questions/10489432/creating-strings-than-can-be-used-as-filepath-eclipse-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!