【发布时间】:2015-05-17 19:57:14
【问题描述】:
我正在创建此活动,其中使用import java.util.Random;,它从arrays.xml 内的字符串数组中获取一个问题。从数组中获取的项目显示在我布局顶部的文本视图中。我想在这里实现的是从字符串数组中获取的每个项目都有一个匹配的背景。我的方法是匹配从问题数组中提取的生成索引并创建一个 if 语句。如果 item=0,则此背景在代码中显示为 *。这是我迄今为止实现的,欢迎对我的代码提出任何建议或改进:
Activity
questions = getResources().getStringArray(R.array.questions);
@SuppressLint("NewApi") private void getQuestion(){
TextView questionText = (TextView) findViewById(R.id.question);
Random rand = new Random();
int maxIndex = questions.length;
int generatedIndex = rand.nextInt(maxIndex);
if(generatedIndex == 1){
**screenGame.setBackground(getResources().getDrawable(R.drawable.footballfindtheposition));
}
else
screenGame.setBackground(getResources().getDrawable(R.drawable.mainbg));
questionText.setText(questions[generatedIndex]);
}**
数组.xml
<string-array name="questions">
<item>Click on the player with the possition of a Center Back</item>
<item>Click on the Player with the possition of Left Center Midfield</item>
<item>Click on the blabla</item>
</string-array>
我在 LogCat 中的代码末尾收到 NullPointerException
【问题讨论】: