こんにちは、RelativeLayoutを持っていて、 "TableLayout"のような6つのボタンを表示したいと思っています。最後のボタンだけが表示されます。TableLayoutのようなRelativeLayout
私は6つのボタン(buttonsperscreen = 6)でアクティビティを試行しています。
私を助けることができますか?
コードは次のとおりです。
private void doLayoutWithButtons(int buttonsperscreen) {
// if total butons is % 2 == 0
if (buttonsperscreen % 2 == 0) {
// get display dimensions
DisplayMetrics d = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(d);
int w = d.widthPixels;
int h = d.heightPixels;
// calc size of buttons
int widthButton = w/2; // only two columns of buttons.
int heightButton = h/((buttonsperscreen)/2); // sample 100px/
// (6/2) = 3
int posx = 0;
int posy = 0;
for (int i = 1; i <= buttonsperscreen; i++) {
Button newButton = new Button(this);
newButton.setId(100 + i + 1); // ID of zero will not work
newButton.setText("Botão: " + i);
// atribuindo o tamanho do botão.
newButton.setHeight(heightButton);
newButton.setWidth(widthButton);
newButton.setId(1000 + i);
// positioning buttons...
RelativeLayout layout1 = new RelativeLayout(this);
// set layout with size of button
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
widthButton, heightButton);
params.leftMargin = posx;
params.topMargin = posy;
newButton.setLayoutParams(params);
layout1.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
layout1.addView(newButton);
setContentView(layout1);
// to calc positions x,y for each button for next iteration
if (posx + widthButton < w) {
posx = posx + widthButton;
} else {
posx = 0;
posy = posy + heightButton;
}
}
}
}
おかげ マテウス
XMLを使用して希望するレイアウトを描画しますか? – Gopal
リニアレイアウトのような相対レイアウトを使いたいのであれば、なぜリニアレイアウトを使っていないのですか? –