简体   繁体   English

可变地访问资源“ R.string”

[英]Accessing a resource “R.string” variably

In my R.string file I have some questions = R.string.question1, R.string.question2, etc. 在我的R.string文件中,我有一些问题= R.string.question1,R.string.question2等。

When the user clicks a button, with only a number as the text, I want to pull that number(num) and access the string at the correct position (R.string.question[num]) 当用户单击仅以数字作为文本的按钮时,我要拉出该数字(数字)并在正确的位置访问字符串(R.string.question [num])

OnClickListener clickQuestion2 = new OnClickListener(){

    @Override
    public void onClick(View arg0) {
        String num = "R.string"+".question"+((Button)arg0).getText().toString();
        int myQuestion = Integer.parseInt(num);
        question.setText(myQuestion);
        int myOption1 = R.string.question2_1;
        int myOption2 = R.string.question2_2;
        int myOption3 = R.string.question2_3;
        int myOption4= R.string.question2_4;
        option1.setText(myOption1);
        option2.setText(myOption2);
        option3.setText(myOption3);
        option4.setText(myOption4); 

Here's the onClickListener for the button. 这是按钮的onClickListener。 I've tried a couple ways, but nothing seems to work. 我尝试了几种方法,但似乎没有任何效果。 The error tells me "R.string.question2", for example, is an invalid string. 该错误告诉我“ R.string.question2”,例如,它是无效的字符串。 So I know I'm passing it the string for the resource I want, I just don't know how to tell it I want it to read that string, find that resource and parse the int that comes with it. 所以我知道我正在为它传递所需资源的字符串,我只是不知道如何告诉我要它读取该字符串,找到该资源并解析其附带的int。 Basically the same as with 基本上与

int myOption1 = R.string.question2_1;

does. 确实。 These are the possible answers to the question being pulled from R.string.question(x), and these work. 这些是从R.string.question(x)中提取问题的可能答案,并且可以正常工作。 How can I get that int for the resource, but change the resource each time a button is clicked. 如何获取资源的int值,但是每次单击按钮时更改资源。

If that makes sense, thanks for the help! 如果这有意义,则感谢您的帮助!

EDIT: "question" is a TextView as well as option1, option2, etc. 编辑:“问题”是TextView以及option1,option2等。

String dynamicString = "question2_1";
int resID = getResources().getIdentifier(dynamicString, "string",  activity.getPackageName()); 
String result = activity.getResources().getString(resID);

Use a String array: 使用字符串数组:

<string-array name="question2">
    <item>Sort By Price</item>
    <item>Sort By Magnitude</item>
    <item>Sort By Ingredient Names</item>
    <item>Sort By Extra Effects</item>
</string-array>

Access in code: 用代码访问:

int myQuestion = Integer.parseInt(num);
option1.setText(question2[myQuestion]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM