将字符串从 Java class 迁移到资源
Migrate String from Java class to resources
我正在做一个测验问题。
我有 "Questions.java"
package com.example.luisbalmant.quickquiz_science;
import android.widget.TextView;
/**
* Created by LuisBalmant on 15/07/2017.
*/
public class Questions {
public String mQuestions[] = {
"My question here",
};
}
我正在尝试在 "My question here" 上使用 "strings.xml" 的字符串语言。
例如:
<string name="Q1_function_insulin">What is the function of insulin?</string>
我正在尝试这个:
getString(R.string.Q1_function_insulin),
有人可以帮我吗?
如果我答对了你的问题,我假设你想从 strings.xml 文件中加载所有问题并将它们放在 mQuestions 数组中。你在那里写的(getString(R.string.Q1_function_insulin)
)应该没有任何问题。我建议您将所有问题放在 xml 内的一个数组中,然后使用 getStringArray(R.array.questions)
.
一次加载整个数组
您需要一个 Context
对象才能执行 getString()
。因此,您可以这样重构 class:
public class Questions {
private static final int QUESTIONS[] = {
R.string.text1,
R.string.text2
};
private Context context;
public Questions(Context context) {
this.context = context;
}
public String getString(int index) {
return context.getString(QUESTIONS[index]);
}
}
然后,从你的 activity:
Questions questions = new Questions(MainActivity.this);
questions.getString(0);
我正在做一个测验问题。
我有 "Questions.java"
package com.example.luisbalmant.quickquiz_science;
import android.widget.TextView;
/**
* Created by LuisBalmant on 15/07/2017.
*/
public class Questions {
public String mQuestions[] = {
"My question here",
};
}
我正在尝试在 "My question here" 上使用 "strings.xml" 的字符串语言。
例如:
<string name="Q1_function_insulin">What is the function of insulin?</string>
我正在尝试这个:
getString(R.string.Q1_function_insulin),
有人可以帮我吗?
如果我答对了你的问题,我假设你想从 strings.xml 文件中加载所有问题并将它们放在 mQuestions 数组中。你在那里写的(getString(R.string.Q1_function_insulin)
)应该没有任何问题。我建议您将所有问题放在 xml 内的一个数组中,然后使用 getStringArray(R.array.questions)
.
您需要一个 Context
对象才能执行 getString()
。因此,您可以这样重构 class:
public class Questions {
private static final int QUESTIONS[] = {
R.string.text1,
R.string.text2
};
private Context context;
public Questions(Context context) {
this.context = context;
}
public String getString(int index) {
return context.getString(QUESTIONS[index]);
}
}
然后,从你的 activity:
Questions questions = new Questions(MainActivity.this);
questions.getString(0);