首页 > 解决方案 > ScrollView 使内部 GridLayout 消失

问题描述

我的目标:制作某种可滚动的画廊(为了改变)。我使用带有 CardView 的 GridLayout。

我已经阅读了很多线程,发现我需要插入一个 ScrollView 并将我的要滚动的内容放入其中。问题是:当我添加 ScrollView 时,为什么我的要滚动的内容会消失?

如果没有 ScrollView,它会完美显示(除了所有内容都显示在同一个“页面”上,因此太小了)。

你能解释一下为什么它不起作用吗?

非常感谢 :)

这是我的 xml 代码:

<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"
    tools:context=".RecipeActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <GridLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="8"
            android:alignmentMode="alignMargins"
            android:columnOrderPreserved="false"
            android:rowCount="3"
            android:columnCount="2">

            <android.support.v7.widget.CardView
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_columnWeight="1"
                android:layout_rowWeight="1">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:focusable="true"
                    android:clickable="true"
                    android:onClick="seeRecipe">

                    <ImageView
                        android:layout_width="0dp"
                        android:layout_weight="1"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:src="@drawable/chocolatine"/>

                    <!-- random TextView -->

                </LinearLayout>

            </android.support.v7.widget.CardView>

            <!-- 15 more android.support.v7.widget.CardView -->

        </GridLayout>

    </ScrollView>

</LinearLayout>

我的java代码是空的,除了必要的东西(onCreate ...)。

标签: androidscrollviewandroid-gridlayout

解决方案


修剪东西的方式,我看到这个:

<GridLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="8"

这个 GridLayout 的父标签是 a <ScrollView>,而 ScrollViews支持布局权重的概念。这意味着您只是将您GridLayout的高度定义为零,这就是它不再显示的原因。

在我看来,您可以通过删除layout_weight属性并将高度设置为来解决这个问题wrap_content


推荐阅读