我想有一个2x2网格内的按钮。这只是ICS,所以我试图使用新的GridLayout给定。
这是我的布局的XML:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/favorites_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
android:rowCount="2"
android:columnCount="2">
<Button
android:text="Cell 0"
android:layout_row="0"
android:layout_column="0"
android:textSize="14dip" />
<Button
android:text="Cell 1"
android:layout_row="0"
android:layout_column="1"
android:textSize="14dip" />
<Button
android:text="Cell 2"
android:layout_row="1"
android:layout_column="0"
android:textSize="14dip" />
<Button
android:text="Cell 3"
android:layout_row="1"
android:layout_column="1"
android:textSize="14dip" />
</GridLayout>
问题是我的视图没有为每一行均匀地拉伸。这导致GridLayout的右侧有很多额外的空间。
我尝试设置layout_gravity="fill_horizontal",但这只适用于该行的最后一个视图。这意味着单元格1会一直延伸,为单元格0提供足够的空间。
如何解决这个问题?
结果:
试试这样做:
final int MAX_COLUMN = gridView.getColumnCount(); //5
final int MAX_ROW = gridView.getRowCount(); //7
final int itemsCount = MAX_ROW * MAX_COLUMN; //35
int row = 0, column = 0;
for (int i = 0; i < itemsCount; i++) {
ImageView view = new ImageView(this);
//Just to provide alternate colors
if (i % 2 == 0) {
view.setBackgroundColor(Color.RED);
} else {
view.setBackgroundColor(Color.GREEN);
}
GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(row, 1F), GridLayout.spec(column, 1F));
view.setLayoutParams(params);
gridView.addView(view);
column++;
if (column >= MAX_COLUMN) {
column = 0;
row++;
}
}
如果你想要单元格的特定宽度和高度,那么使用:
params.width = 100; // Your width
params.height = 100; //your height
你可以通过重写ViewGroup onLayout方法来提高速度。
这是我的普遍解决方案:
package your.app.package;
import android.content.Context;
import android.view.ViewGroup;
public class GridLayout extends ViewGroup {
public GridLayout(Context context) {
super(context);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int columns = 2;//edit this if you need different grid
final int rows = 2;
int children = getChildCount();
if (children != columns * rows)
throw new IllegalStateException("GridLayout must have " + columns * rows + " children");
int width = getWidth();
int height = getHeight();
int viewWidth = width / columns;
int viewHeight = height / rows;
int rowIndex = 0;
int columnIndex = 0;
for (int i = 0; i < children; i++) {
getChildAt(i).layout(viewWidth * columnIndex, viewHeight * rowIndex, viewWidth * columnIndex + viewWidth, viewHeight * rowIndex + viewHeight);
columnIndex++;
if (columnIndex == columns) {
columnIndex = 0;
rowIndex++;
}
}
}
}
编辑:
不要忘记match_parent for children!
android:layout_width="match_parent"
android:layout_height="match_parent"