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

标签 android android-gridlayout

我们需要在 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_horizo​​ntal" 部分。那只是我的尝试。)

还有那个 XML(或通过在代码中做同样的事情)我最终在最终结果中得到了不均匀间隔的列。看起来包含内容(文本)更宽的单元格的列总体上有更多的空间。我怎样才能避免这种情况?

您可以在下图中看到结果,尽管乍一看可能几乎看不出来。仅包含 10dp 宽的 Space View 的单元格最引人注目。 enter image description here

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

最佳答案

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

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

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

支持库有一个更好的 GridLayout .它允许您为每个 View 指定权重,这意味着您可以通过让每个 View 具有相同的权重来平均分配空间。

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

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

关于android - 具有均匀间隔控件的动态 GridLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35205621/

相关文章:

Android 单选按钮

android - putExtra 数据不在 Activity 之间传递

android - 试图重新打开一个已经关闭的对象 : SQLiteDatabase:

android - 使用 GridLayoutManager 和 RecyclerView 更改列数

android - Xamarin android、Xamarin iOS 和 Xamarin 跨平台项目之间的区别

android - 自定义可扩展 ListView 添加按钮

java - Android Studio > GridLayout > 如何获取单元格的位置?

具有多行的android LinearLayout

android - GridLayout 中的空单元格收缩

android gridlayout 未在模拟器 API 22 中显示