【问题标题】:random number from string-array matching a background匹配背景的字符串数组中的随机数
【发布时间】: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

【问题讨论】:

    标签: java android arrays


    【解决方案1】:

    您可以在包含可绘制对象的arrays.xml 中定义另一个数组。确保它与您的问题数组大小相同:

    <string-array name="backgrounds">
        <item>@drawable/footballfindtheposition</item>
        <item>@drawable/midfieldfindtheposition</item>
        <item>@drawable/blabla...</item>    
    </string-array>
    

    然后在您的代码中,将其加载为TypedArray:

    TypedArray backgrounds = getResources().obtainTypedArray(R.array.backgrounds);
    

    TypedArray 中有不同的函数允许您将内容解释为不同的事物(例如资源 ID、维度、文本、整数等)。

    您可以使用 getResourceId() 将值作为资源 id 查找,它返回一个 int:

    TypedArray backgrounds = getResources().obtainTypedArray(R.array.backgrounds);
    int maxIndex = questions.length;
    int generatedIndex = rand.nextInt(maxIndex);
    screenGame.setBackground(getResources().getDrawable(backgrounds.getResourceId(generatedIndex,-1));
    questionText.setText(questions[generatedIndex]);
    backgrounds.recycle();
    

    这样做意味着您不必有很长的 if 语句,并且您可以就地管理您的背景可绘制对象和问题 (arrays.xml)

    【讨论】:

    • 有没有办法将 arrayList 中的 objectIndex 与同一或另一个 arrayList 上的另一个 objectIndex 匹配?
    • 使用 for-each 结构迭代 A​​rrayList:stackoverflow.com/a/6700737/696391
    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 2014-05-13
    • 2011-09-16
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 2014-01-19
    • 2018-10-09
    相关资源
    最近更新 更多