我在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++;
}
}
答案 0 :(得分: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++;
}
}