Anton Makov
Anton Makov

Reputation: 123

Dynamically create a matrix of ImageViews in RelativeLayout

I'm having an issue with creating a matrix of images in RelativeLayout. I manged to create only one row of it, the other rows are just not showing at all.

int index=1;
    for(int i=0;i<Globals.NUM_ROWS;i++){
        for(int j=0;j<Globals.NUM_COLS;j++)
        {
            ImageView iv = new ImageView(this);
            iv.setImageResource(R.drawable.obs_block);
            iv.setId(index);
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);

            if(i!=0 && i%Globals.NUM_COLS==0){
                lp.addRule(RelativeLayout.BELOW,index-Globals.NUM_COLS);
            }else{
                lp.addRule(RelativeLayout.RIGHT_OF, index-1);
            }

            gameLayout.addView(iv, lp);
            index++;
        }
    }

Upvotes: 0

Views: 2295

Answers (1)

user
user

Reputation: 87064

You don't build the Relative.LayoutParams correctly. See if this helps:

        int index = 1;
        for (int i = 0; i < Globals.NUM_ROWS; i++) {
            for (int j = 0; j < Globals.NUM_COLS; j++) {
                ImageView img = new ImageView(this);
                img.setId(index);
                img.setImageResource(R.drawable.ic_launcher);
                RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                if (j == 0) {
                    rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT,
                            RelativeLayout.TRUE);
                } else {
                    rlp.addRule(RelativeLayout.RIGHT_OF, index - 1);
                }
                if (i == 0) {
                    rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP,
                            RelativeLayout.TRUE);
                } else {
                    rlp.addRule(RelativeLayout.BELOW, index - Globals.NUM_COLS);
                }
                img.setLayoutParams(rlp);
                rl.addView(img);
                index++;
            }
        } 

Upvotes: 1

Related Questions