android –如何在GridLayout中保留空白

时间:2019-02-23 17:22:05

标签: android android-gridlayout

我有GridLayout(来自支持库),其中有两行按钮。所有按钮的宽度设置为2,高度设置为1。第一行应向右移动一个位置。当我这样做时,GridLayout的工作方式就像第一行没有移动一样。

第二行:

GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.rowSpec = GridLayout.spec(1, 1, 1);
params.columnSpec = GridLayout.spec(x, 2, 1);

第一行:

GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.rowSpec = GridLayout.spec(0, 1, 1);
params.columnSpec = GridLayout.spec(x + 1, 2, 1);

2 个答案:

答案 0 :(得分:0)

您必须在顶部和左侧的所有单元格(开始)中插入虚拟视图。

for (int x = 0; x < gridLayout.getColumnCount(); x++) {
    GridLayout.LayoutParams params = new GridLayout.LayoutParams();
    params.rowSpec = GridLayout.spec(0, 1, 1);
    params.columnSpec = GridLayout.spec(x, 1, 1);
    params.setGravity(Gravity.FILL);
    params.width = 0;
    gridLayout.addView(new Space(this), params);
}
for (int y = 0; y < gridLayout.getRowCount(); y++) {
    GridLayout.LayoutParams params = new GridLayout.LayoutParams();
    params.rowSpec = GridLayout.spec(y, 1, 1);
    params.columnSpec = GridLayout.spec(0, 1, 1);
    params.setGravity(Gravity.FILL);
    params.width = 0;
    gridLayout.addView(new Space(this), params);
}

答案 1 :(得分:0)

这是我想出的更好的(IMO)解决方案;

<GridLayout
    android:orientation="horizontal"
    android:columnCount="3"
    android:useDefaultMargins="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Space android:layout_columnWeight="1" />
    <Space android:layout_columnWeight="1" />
    <Space android:layout_columnWeight="1" />

    <TextView
        android:text="01"
        android:layout_columnWeight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textColor="@color/colorWhite"
        android:background="@color/colorBlack"
        android:padding="15dp" />

    <TextView
        android:text="02"
        android:layout_columnWeight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textColor="@color/colorWhite"
        android:background="@color/colorBlack"
        android:padding="15dp" />


    <!-- REPEAT ITEM HOWEVER MANY TIMES -->


</GridLayout>

这是在网格中使用4、3、2和1项以及默认边距添加到GridLayout的方式进行渲染的方式;

Shows how GridLayout renders with 4, 3, 2 or 1 items