0

我在创建图像矩阵时遇到问题RelativeLayout。我设法只创建了一行,其他行根本没有显示。

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++;
        }
    }
4

1 回答 1

1

您没有Relative.LayoutParams正确构建。看看这是否有帮助:

        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++;
            }
        } 
于 2012-08-04T10:11:02.227 回答