具有均匀间隔控件的动态 GridLayout

Dynamic GridLayout with evenly spaced controls

我们需要在 Grid 中放置任意控件,支持 colspan(并且可能进一步支持 rowspan)。所以我在看 Android's GridLayout,因为它似乎只是支持它。我设置了一个简单的例子,只是将 TextView 放在一些单元格中。

我的 XML 看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#cccccc"
    android:orientation="horizontal"
    android:weightSum="1"
    android:id="@+id/root">
    <GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:background="@android:color/holo_green_dark" android:layout_weight="1">
        <TextView android:text="Erstes" android:layout_row="0" android:layout_column="0" android:layout_columnSpan="2" android:layout_columnWeight="1"  android:background="#333333" />
        <TextView android:text="Zweites" android:layout_row="1" android:layout_column="2" android:layout_columnWeight="1"  android:background="#666666" />
        <TextView android:text="Drittes" android:layout_row="1" android:layout_column="1" android:layout_columnWeight="1"  android:background="#888888"/>
        <TextView android:text="Viertes" android:layout_row="2" android:layout_column="3" android:layout_columnWeight="1"  android:background="#aaaaaa" />
        <Space android:layout_row="1" android:layout_column="0" android:layout_width="10dp" android:layout_columnWeight="1" android:layout_gravity="fill_horizontal" />
    </GridLayout>
</LinearLayout>

必须在其中放入具有固定宽度的 Space,以免第二行中的第一个单元格折叠。我的第一个问题是,是否有另一种方法可以做到这一点?因为我想避免设置任何内容的宽度,因为事先并不知道每个单元格的列数和相应位置。 (编辑:我想你可以忽略其中的 android:layout_gravity="fill_horizontal" 部分。那只是我在尝试。)

还有那个 XML(或者通过在代码中做同样的事情)我最终在最终结果中得到不均匀的 spaced 列。似乎包含内容(文本)更宽的单元格的列总体上被赋予更多 space。我怎样才能避免这种情况?

您可以在下图中看到结果,虽然乍一看可能几乎看不出来。最引人注目的是仅包含 10dp 宽 Space 视图的单元格。

我是不是对这里的 GridLayout 期望太高了?感谢您的帮助!

对于您的第一个问题,显而易见的答案可能是在缺少控件的地方添加 Space 视图,并将所有视图设置为具有相同的权重。

对于第二期,最好将 layout_width 设置为 0dp,因为它们默认设置为 wrap_content。

忽略以下内容,因为您已经在使用 API 21.

支持库有更好的 GridLayout。它允许您为每个视图指定权重,这意味着您可以通过让每个视图具有相同的权重来均匀分布 space。

更具体地说,将 compile "com.android.support:gridlayout-v7:${SUPPORT_LIBRARY}" 添加到 Gradle 依赖项列表中,其中 ${SUPPORT_LIBRARY} 是可用的最新版本。

并使用 android.support.v7.widget.GridLayout 标签进行布局。