我正在尝试使用单元格和行填充填充整个屏幕的表格布局。像这样:
http://imageshack.us/photo/my-images/69/device20120201005942.png/
在 Eclipse 的图形布局窗口中设计的这个布局给出了我想要的(android:layout_weight 解决了垂直拉伸):
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:stretchColumns="*" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" android:layout_weight="1">
<ImageView
android:id="@+id/imageView1"
android:layout_gravity="center"
android:src="@drawable/add" />
<ImageView
android:id="@+id/imageView2"
android:layout_gravity="center"
android:src="@drawable/bound" />
<ImageView
android:id="@+id/imageView3"
android:layout_gravity="center"
android:src="@drawable/cod" />
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1" >
<ImageView
android:id="@+id/imageView4"
android:layout_gravity="center"
android:src="@drawable/delete" />
<ImageView
android:id="@+id/imageView5"
android:layout_gravity="center"
android:src="@drawable/delete2" />
<ImageView
android:id="@+id/imageView6"
android:layout_gravity="center"
android:src="@drawable/floppy" />
</TableRow>
</TableLayout>
我正在尝试在代码中创建相同的外观,但到目前为止失败了。这是我的活动的 oncreate:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tablelo);
TableLayout tl = (TableLayout) findViewById(R.id.table);
Log.d(TAG, "Width :" + tl.getWidth());
for (int row = 0; row < 3; row++) {
TableRow tr = new TableRow(this);
tr.setId(100 + row);
for (int cell = 0; cell < 3; cell++) {
ImageView image = new ImageView(this);
image.setImageResource(imageIDs[row * 3 + cell]);
tr.addView(image);
}
tr.setGravity(Gravity.CENTER);
LayoutParams params = new TableRow.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1);
tr.setLayoutParams(params);
tl.addView(tr, params);
}
tl.setStretchAllColumns(true);
}
我缺少设置 ImageView 重力的代码,但此尝试会导致崩溃:
image.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER));
此代码创建了 3 行,每行水平但不垂直拉伸:
http://imageshack.us/photo/my-images/835/gridc.png/
我在这里找不到我所缺少的。我还尝试在设计器中准备一个表格,并在运行时膨胀并添加到表格中,但结果没有改变。
因此,不知何故,我想以编程方式获得可以使用 editor 创建的相同布局。
请帮忙!