我试图使用FrameLayout以编程方式使用具有特定尺寸4x4的按钮制作矩阵。
button = new Button[16];
for(int i = 0; i < button.length; i++)
{
button[i] = new Button(this);
button[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
button[i].setText("" + i);
button[i].setOnClickListener(this);
frameLayout.addView(button[i]);
}
在这里,我创建了按钮,但在运行程序时它们重叠。
如果有人能告诉我如何在frameLayout中对齐按钮以制作4x4矩阵,我真的很感激?
答案 0 :(得分:0)
试试这个,
将它放在你的xml中:
<LinearLayout
android:id="@+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"/>
并将此代码放入您的活动中:
LinearLayout linearlayout = (LinearLayout) findViewById(R.id.linearlayout);
for (int i = 1; i <= 4; i++) {
LinearLayout linearLayoutHoriztonal = new LinearLayout(this);
linearLayoutHoriztonal.setOrientation(LinearLayout.HORIZONTAL);
for (int j = 1; j <= 4; j++) {
linearLayoutHoriztonal.addView(createButton("" + i));
}
linearlayout.addView(linearLayoutHoriztonal);
}
添加此方法以创建按钮:
private Button createButton(String number) {
Button button = new Button(this);
button.setText(number);
button.setPadding(5, 0, 5, 0);
button.setTextSize(14f);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(WRAP_CONTENT, convertToPixel(40));
layoutParams.setMargins(convertToPixel(10), convertToPixel(10), 0, 0);
button.setLayoutParams(layoutParams);
return button;
}
private int convertToPixel(int n) {
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, n, r.getDisplayMetrics());
return (int) px;
}