首页 > 解决方案 > 在 GridLayout 单元格周围添加边距

问题描述

我试图弄清楚如何在添加到 GridLayout 的片段周围添加边距。

GridLayout gridLayout = mRegionPage.findViewById(R.id.xglRegionPage);

GridLayout.MarginLayoutParams foo = 
        new GridLayout.MarginLayoutParams(GridLayout.LayoutParams.WRAP_CONTENT, 
                                          GridLayout.LayoutParams.MATCH_PARENT);

foo.setMargins(20, 20, 20, 20);
gridLayout.setLayoutParams(foo);

xml 资源看起来像

<GridLayout
    android:id="@+id/xglRegionPage"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:rowCount="2"
    ... />

我有一个错误是:

java.lang.ClassCastException: android.view.ViewGroup$MarginLayoutParams 
            cannot be cast to android.widget.FrameLayout$LayoutParams
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:186)
    at android.widget.HorizontalScrollView.onMeasure(HorizontalScrollView.java:491)

如果我注释掉设置布局参数的行,则没有错误。

GridLayout gridLayout = mRegionPage.findViewById(R.id.xglRegionPage);

GridLayout.MarginLayoutParams foo = 
        new GridLayout.MarginLayoutParams(GridLayout.LayoutParams.WRAP_CONTENT, 
                                          GridLayout.LayoutParams.MATCH_PARENT);

foo.setMargins(20, 20, 20, 20);
///gridLayout.setLayoutParams(foo);

我的问题是我不在任何项目中使用单个 FrameLayout。我检查了我使用的所有工具包部件,它们都不是 FrameLayout 的子类。

有没有其他方法可以做到这一点?

FrameLayout 是如何混入这一切的?还是 GridLayout 是围绕 FrameLayout 构建的?

如果我想有两排卡片,它们之间有一些空间,是否必须使用两个线性布局?

有人建议我在片段的底部添加边距,我已经拥有但没有任何效果。他们看起来像:

<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"

  android:id="@+id/clRegionFragment"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  android:background="@drawable/excited_shape"
  android:layout_marginRight="50dp"
  android:layout_marginLeft="50dp"
  android:layout_marginTop="50dp"

标签: androidandroid-gridlayout

解决方案


(代表问题作者发布,将解决方案移至答案空间)

问题是我在片段膨胀之前添加的 GridLayout.LayoutParams 中,从而消除了片段 xml 中的任何值。相反,我将网格位置的行和列添加到片段中,在片段膨胀后,我设置了网格行和列规范的参数。


推荐阅读