首页 > 解决方案 > 如何在 GridLayout 中将 ImageView 居中?

问题描述

我有一个全屏网格布局,有 8 行,每行 7 个 ImageView。我需要所有居中的行,它们之间没有空格(现在我有我上传的图像)。该空间必须仅在顶部和底部。我已经尝试在 Internet 上找到解决方案,但我还没有找到。

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">

    <GridLayout
        android:id="@+id/gameGrid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:rowCount="8"
        android:columnCount="7"
        >
        <!-- ROW 1-1 -->
        <ImageView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:id="@+id/cellR1-1"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            app:srcCompat="@drawable/dl"
            />
        <!-- ROW 1-2 -->
        <ImageView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:id="@+id/cellR1-2"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            app:srcCompat="@drawable/dl"
            />
        <!-- ROW ... -->
    </GridLayout>
</RelativeLayout>

我尝试将所有 ImageViews 高度设置为与宽度相同的解决方案,但我的代码不起作用:

void setGrid(){
    //setting the cell height as the cell widht
    int imagWidth = cell[0][0].getLayoutParams().width;
    for(int r=0;r<rowCount;r++)
        for(int c=0;c<columnCount;c++) {
            cell[r][c].getLayoutParams().height = imagWidth;
            cell[r][c].requestLayout();
        }
}

图片:
图片

标签: androidimageviewandroid-gridlayout

解决方案


它可能对你有帮助,使用 RecyclerView 而不是 GridLayout

RecyclerView.LayoutManager recyclerViewLayoutManager = new GridLayoutManager(getApplicationContext(), 7); // 7 means how many column you want you can change according to your requirement.
recyclerView.setLayoutManager(recyclerViewLayoutManager);

推荐阅读