我正在尝试为游戏编写菜单,现在想要进行关卡选择。它应该有三行,每行有 5 个按钮。
for(int i=0; i<3; ++i){
for(int j=0; j<5; ++j){
ImageButton button = new ImageButton(this);
RelativeLayout.LayoutParams paramsBut = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
paramsBut.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
paramsBut.addRule(RelativeLayout.ALIGN_PARENT_TOP);
int marginLeft = (int)((float)(sizeLeftWidth/6) * (j+1)) + j*buttonSize;
int marginTop = (int)((float)(sizeLeftHeight/4) * (i+1)) + i*buttonSize;
paramsBut.leftMargin = marginLeft;
paramsBut.topMargin = marginTop;
button.setAdjustViewBounds(true);
button.setMaxWidth(buttonSize);
button.setMaxHeight(buttonSize);
button.setBackgroundDrawable(null);
Bitmap bmp = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.level),buttonSize,buttonSize,false);
Drawable d = new BitmapDrawable(bmp);
button.setImageDrawable(d);
layout.addView(button,paramsBut);
}
}
相对布局:
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
layout.setLayoutParams(params);
问题是按钮不在正确的位置,我认为问题出在边距上。我在边距上做得对还是整个代码完全愚蠢?(如果我得到提示如何改进我的编程风格,我总是很高兴^^)