Android GridLayout实现2x2布局时CardView占满屏出界问题
GridLayout 2x2 卡片布局修正方案
问题根源
你遇到的单卡片占满全屏、第二张卡片偏移到屏幕外的问题,核心来自尺寸配置错误:
- androidx 版本的 GridLayout 不会自动拆分设置为
match_parent的子项宽度,第一个子项会直接以整个 GridLayout 的总宽度作为自身占位 - 第一列的卡片占满全部宽度后,第二列的卡片没有剩余排布空间,自然会被挤到可视区域外
- 当前代码没有给网格列/行配置权重,两列不会自动均分 GridLayout 的总可用宽度
修正操作
- 把所有网格内 CardView 的宽、高属性调整为
0dp,不要使用match_parent或wrap_content - 给每个 CardView 添加横向权重
app:layout_columnWeight="1",实现两列等宽分配空间 - 给每个 CardView 添加纵向权重
app:layout_rowWeight="1",实现两行等高分配空间 - 根据视觉需求给 CardView 设置
layout_margin,作为卡片之间、卡片与屏幕边缘的间距
可直接运行的修正后代码
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.gridlayout.widget.GridLayout android:layout_width="match_parent" android:layout_height="match_parent" app:columnCount="2" app:rowCount="2" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <androidx.cardview.widget.CardView android:layout_width="0dp" android:layout_height="0dp" app:layout_row="0" app:layout_column="0" app:layout_rowWeight="1" app:layout_columnWeight="1" android:layout_margin="8dp"/> <androidx.cardview.widget.CardView android:layout_width="0dp" android:layout_height="0dp" app:layout_row="0" app:layout_column="1" app:layout_rowWeight="1" app:layout_columnWeight="1" android:layout_margin="8dp"/> <androidx.cardview.widget.CardView android:layout_width="0dp" android:layout_height="0dp" app:layout_row="1" app:layout_column="0" app:layout_rowWeight="1" app:layout_columnWeight="1" android:layout_margin="8dp"/> <androidx.cardview.widget.CardView android:layout_width="0dp" android:layout_height="0dp" app:layout_row="1" app:layout_column="1" app:layout_rowWeight="1" app:layout_columnWeight="1" android:layout_margin="8dp"/> </androidx.gridlayout.widget.GridLayout> </androidx.constraintlayout.widget.ConstraintLayout>
注意:权重逻辑生效的前提是子项宽高设为0dp,如果保留match_parent设置,权重无法正常计算空间分配,会再次出现布局偏移问题。
内容的提问来源于stack exchange,提问作者AwesomeGuy
相关产品推荐
相关产品推荐

