【问题标题】:My gridlayout is not inflating as expected我的网格布局没有按预期膨胀
【发布时间】:2018-01-17 14:59:27
【问题描述】:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.package.name.MainActivity">

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnCount="4"
        android:rowCount="4">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_column="1"
            android:layout_row="2"
            android:src="@color/colorAccent"/>

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_column="3"
            android:layout_row="2"
            android:src="@color/colorPrimary"/>

    </GridLayout>

</LinearLayout>

这是我的布局文件。我期待一个 4x4 网格,第 1 列第 2 行中的强调色和第 3 列第 2 行中的原色,其余为空白。但相反,我只是让整个网格布局充满了强调色,甚至没有一个具有原色的单元格。为什么是这样?如何实现我想要的?

谢谢!

【问题讨论】:

    标签: android android-layout grid-layout android-gridlayout


    【解决方案1】:

    您的第一个ImageView 的宽度和高度为match_parent,因此它自己填充了整个布局。只需为每个ImageView 定义宽度和高度,例如100dp,您就可以看到您想看到的东西。这不是你想要的,但它可以让你开始。另外,请查看https://developer.android.com/reference/android/widget/GridLayout.html 上的“Excess Space Distribution”。

    【讨论】:

    • 好的,有趣。因此,当我将高度和宽度设置为 100dp 时,我确实得到了 2 个单独的框,每个 100dp x 100dp 但它们不在我想要的单元格中。它们位于屏幕的左上角和右上角,尽管我已经为每个定义了layout_columnlayout_row。我正在查看有关此的文档,但对我来说并不是很清楚。我以为我可以把它当作一个网格来处理?
    • @intA 我认为您需要定义每个单元格。你说得对,这个ViewGroup 的在线文档或示例并不多。
    • @intA 你见过this tutorial吗?它深入探讨了布局的工作原理。
    • 谢谢,我去看看。虽然我刚刚找到了 TableLayout 并且对于我的情况可能更容易使用。或者是一个包含 4 个水平 LinearLayouts 的 LinearLayout。
    • @intA TableLayout 非常直观。您还可以考虑 ConstraintLayout 中的链以获得更扁平的布局结构。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多