android填充数组与string.xml中的字符串

时间:2014-01-20 23:04:23

标签: android

到目前为止我学到了什么:

在strings.xml中我有很多

<string name="q1">what is the name of blah blah</string>
<string name="q2">what is the name of blah blah</string>
<string name="q3">what is the name of blah blah</string>
<string name="q4">what is the name of blah blah</string>

并且在主类中我必须创建一个问题对象数组来访问它们 整个主要课程如

 private Question[] mQuestionList = new Question[]{
  new Question(R.string.q1, true),
  new Question(R.string.q2, false),
  new Question(R.string.q3, true),
  new ...
 }

有什么好奇的是,如果我有200个问题,我知道我必须在stirng.xml文件中写出每个问题,但我认为200“新问题(R.string.qx,true / false)”主类中的语句不是正确的方法。我相信有一些方法可以更轻松地填充mQuestionList数组。如果有什么?

1 个答案:

答案 0 :(得分:4)

您可以将其放在values / arrays.xml

<string-array name="array_name">
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
    <item>5</item>
    <item>6</item>
    <item>7</item>
</string-array>

然后做

String[] questionStrings = getResources().getStringArray(R.arrays.array_name);
mQuestionList = new Question[questionStrings.length];

for (int i = 0; i < questionStrings.length; i++) {
    mQuestionList[i] = new Question( questionStrings[i], ...

如果第二个参数(布尔值)对于每个问题都不同,则在values / arrays.xml中存储一个新数组