Get Resource Id from multiple ImageViews and assign drawable to them

Viewed 108

My app has a GridLayout and 60 ImageViews on it. I want to assign a drawable to 25 cells of grid layout. for that purpose i have an array with 25 random numbers.
then i defined a hashmap that each item is one of the image views:


private  HashMap<Integer, Integer> imageViews = new HashMap<>();
imageViews.put(0, R.id.imageView1);
.
.
.
imageViews.put(59, R.id.imageView60);

and put 60 imgageviews in hashmap ... 0 is id for first imageview. and set drawable to cells with this method:

    private void setBombDrawable(){
    HashMap<Integer, Integer> map = mImageViewsMap.getImageViews();
    for (int tag : randomBombArray) {
        int id = map.get(tag);
        ImageView imageView = findViewById(id);
        imageView.setImageResource(R.drawable.exploded);
    }

}

code runs without problem, but if there is any simpler way for getting imageviews id or tag from grid layout instead of 60 lines of code?

1 Answers

Why just id when you can get the ImageView directly from the GridLayout. GridLayout is a ViewGroup, so you can loop through all of its child view.

private Map<Integer, ImageView> imageViews = new HashMap<>();
int childCount = gridLayout.getChildCount();
for (int i = 0; i < childCount; i++) {
    View v = gridLayout.getChildAt(i);
    if (v instanceof ImageView) {
         map.put(i, (ImageView) v);
    }    
}
Related