android - 如何在 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();
}
}
解决方案
它可能对你有帮助,使用 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);
推荐阅读
- git - 从拉取请求中的提交安装 npm 包
- java - 创建方阵
- bitbucket-pipelines - bitbucket 管道中是否有 if-else 块?
- blazor - 适用于企业的 Blazor 托管模型
- php - AngularJs 中 PHP 的 net::ERR_EMPTY_RESPONSE
- angular - Cordova:在 Angular 8 延迟加载实施后,应用程序无法启动,并且在初始屏幕显示白屏后
- javascript - Chrome 正则表达式匹配不应该匹配的字符
- angular - Angular 8:TypeError:发现不可调用的@@iterator
- ios - 如何快速最小化视频播放器
- php - 执行机器人命令