【发布时间】:2015-07-02 05:38:28
【问题描述】:
我想在表格布局中动态添加一些宽度相等的按钮。我已经尝试过 StackOverflow 的所有方法,但找不到合适的解决方案。
这是我最初的 XML 布局:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/puzzle_background"
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="match_parent"
android:layout_gravity="center">
<TextView
android:text="@string/levels_label"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dip"
android:layout_marginBottom="10dip"
android:textSize="28sp" />
<TableLayout
android:id="@+id/displayLevels"
android:background="@color/puzzle_background"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical" >
</TableLayout>
</LinearLayout>
这是我的代码部分:
int i = 0;
int j = 0;
while (i<levelNum) {
j = i + 4;
row = new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(lp);
row.setWeightSum(4);
while ((i<j)&&(i<levelNum)) {
Button iBtn = new Button(this);
iBtn.setGravity(Gravity.CENTER_HORIZONTAL);
iBtn.setText(Integer.toString(i + 1));
iBtn.setId(i + 1);
iBtn.setOnClickListener(btnclick);
row.addView(iBtn, 4 + i - j);
i++;
}
lTable.addView(row);
}
但每次我在行中获得 4 个按钮时,它们并不真正适合该行。行中的右键总是在屏幕之外。
我做错了什么?请指教。
此致,亚历克斯
【问题讨论】:
标签: android layout android-studio tablelayout