简体   繁体   中英

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:

<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);
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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