简体   繁体   English

Android-从数组动态更改ImageView

[英]Android - Dynamically changing ImageView s from an array

I have an array of Images, and I am trying to change image views to match these drawables. 我有一个图像数组,并且尝试更改图像视图以匹配这些可绘制对象。 For some reason, they are simply not being drawn at all. 由于某些原因,根本根本没有绘制它们。

Here is my code so far: 到目前为止,这是我的代码:

TypedArray answerResources = res.obtainTypedArray(R.array.answers);
int resId = answerResources.getResourceId(randomQuestion, -1);
answerResources.recycle();

int [] questionAnswers = res.getIntArray(resId);

firstAnswerImg .setImageResource(questionAnswers[0]);
secondAnswerImg.setImageResource(questionAnswers[1]);
thirdAnswerImg .setImageResource(questionAnswers[2]);
fourthAnswerImg.setImageResource(questionAnswers[3]);

Here is the xml: 这是xml:

<array name = "answers">
    <item>@array/questionOneAnswers</item>
    <item>@array/questionTwoAnswers</item>
    <item>@array/questionThreeAnswers</item>
...
</array>

    <integer-array name = "questionOneAnswers">
        <item>@drawable/da</item>
        <item>@drawable/sk</item>
        <item>@drawable/cq</item>
        <item>@drawable/ht</item>
    </integer-array>

What am I missing?? 我想念什么?

EDIT: My bad, I see the nesting now. 编辑:我不好,我现在看到嵌套。 I think you need to use typed arrays (just like you did for the outer ones), like so: 我认为您需要使用类型化数组(就像您对外部数组所做的那样),如下所示:

<array name="answers">
  <item>@array/questionOneAnswers</item>
  <item>@array/questionTwoAnswers</item>
  <item>@array/questionThreeAnswers</item>
</array>
...
<array name="questionOneAnswers">
  <item>@drawable/da</item>
  <item>@drawable/sk</item>
  <item>@drawable/cq</item>
  <item>@drawable/ht</item>
</array>

Then, pull from the array like so: 然后,像这样从数组中拉出:

TypedArray answers = res.obtainTypedArray(R.array.answers);
int questionOneAnswersId = answerResources.getResourceId(0, 0));
TypedArray questionOneAnswers = res.obtainTypedArray(questionOneAnswersId);
firstAnswerImg.setImageDrawable(questionOneAnswers.getDrawable(0);
....

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

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