Android开发:10×10星星ImageView网格随机设置可见性报错求助
setVisibility Error in Your 10x10 Star Grid Hey there! Let's break down why that line target.setVisibility(View.VISIBLE); is causing an error—this is a common issue with grid-based View setups, so we'll work through the most likely fixes step by step.
Common Causes & Solutions
1. Your target ImageView is null
This is the #1 culprit. It means your code isn't successfully finding the ImageView for the random coordinates you generated. Here's how to fix it:
- Double-check your ID naming convention. If your XML uses IDs like
star_row_col(e.g.,star_0_0for the top-left star), make sure your string concatenation matches exactly. For example:Random random = new Random(); int row = random.nextInt(10); int col = random.nextInt(10); // Match this string to your XML ID pattern exactly String starId = "star_" + row + "_" + col; // Get the resource ID correctly int resId = getResources().getIdentifier(starId, "id", getPackageName()); ImageView target = findViewById(resId); - If
resIdreturns0, that means the ID doesn't exist in your layout. Check for typos (like missing underscores, wrong numbers, or capitalization mismatches) in both your XML and code.
2. You're modifying the View before it's ready
If you're trying to access the ImageView before setContentView(R.layout.your_main_layout) runs in onCreate, or if you're updating the UI from a background thread, you'll hit errors.
- Ensure all View lookup and modification happens after
setContentViewinonCreate. - If your random generation logic runs on a background thread, wrap the visibility change in
runOnUiThreadto make sure it executes on the main thread:runOnUiThread(() -> { if (target != null) { target.setVisibility(View.VISIBLE); } });
3. Incorrect View type casting
If the ID you're looking up doesn't correspond to an ImageView (e.g., you accidentally reused the ID for a TextView), you'll get a ClassCastException. Add a quick check to confirm:
if (target instanceof ImageView) { target.setVisibility(View.VISIBLE); } else { Log.e("StarGrid", "Found view isn't an ImageView!"); }
4. XML layout issues
- Verify all your star ImageViews have
android:visibility="invisible"set (notgone, though that shouldn't cause a crash here). - Make sure no two Views share the same ID, and all IDs fit your 10x10 range (rows/cols from 0 to 9, no out-of-bounds numbers).
Debugging Tip
Add these log statements right before the problematic line to see exactly what's going wrong:
Log.d("StarGridDebug", "Random row/col: " + row + "/" + col); Log.d("StarGridDebug", "Resource ID found: " + resId); Log.d("StarGridDebug", "Target ImageView: " + target);
If target shows as null in the logs, you know the issue is with finding the correct View ID.
内容的提问来源于stack exchange,提问作者Louis Evans

