获取错误图片索引问题咨询(附array.xml代码片段)
Hey there! Let's figure out why you're getting wrong image indices from your array.xml setup. Based on the code snippet you shared, here are the most likely culprits and fixes to try:
Possible Causes & Solutions
XML Syntax Errors
Looking at your code, the last<item>tag is truncated (<item>@drawable/animal106<...</item>) — that's a critical issue! XML requires all tags to be properly closed. If your actualarray.xmlhas unclosed tags or invalid syntax, the Android resource parser might misinterpret the array structure, leading to incorrect indices or missing entries entirely.
Fix: Double-check your entireinteger-arrayto ensure every<item>is closed with</item>, and there are no typos, missing characters, or truncated lines.Mismatched Resource Expectations vs. Array Order
Your array is ordered asanimal1,animal10,animal100,animal101, etc. If your code expects, say, index 1 to correspond toanimal2(instead ofanimal10), you'll naturally get the wrong image. This is a common logic mismatch, not a bug in the array itself.
Fix: Either reorder the<item>entries inarray.xmlto match your expected sequence (e.g.,animal1,animal2,animal3...), or adjust your code to account for the actual order of the array entries.Missing Drawable Resources
If any@drawable/xxxentry in your array points to a file that doesn't exist in yourres/drawable(or density-specific) folders, Android will fall back to a default resource (or even crash in some cases), making it seem like you're getting the wrong index.
Fix: Verify every drawable referenced in the array exists. Android Studio's resource inspector will highlight any broken references in red, so use that to quickly spot missing files.Incorrect Array Access Logic
If you're generating indices dynamically (like with random numbers), make sure you're not going out of bounds. For example, usingnew Random().nextInt(animalDrawables.length)is safe, but usingnextInt(animalDrawables.length + 1)will cause an index out of bounds exception, which might lead to unexpected behavior if unhandled.
Fix: Add logging to debug your array access. Print out the index you're using and the corresponding drawable name to confirm they match what you expect. Here's a quick snippet to do that:int[] animalDrawables = getResources().getIntArray(R.array.animal); int selectedIndex = // your index logic here String drawableName = getResources().getResourceEntryName(animalDrawables[selectedIndex]); Log.d("ImageDebug", "Selected index: " + selectedIndex + " → Drawable: " + drawableName);This will show you exactly which drawable is being picked for each index, making it easy to spot where the mismatch is.
内容的提问来源于stack exchange,提问作者Kamalesh M. Talaviya

