如何设置GridLayout中子列宽度为父容器宽度的四分之一?
实现GridLayout子列宽度为父容器的1/4(单行仅一列时生效)
原配置里的columnCount="3"和layout_columnWeight="4"无法满足需求,调整以下几点即可实现:
- 把GridLayout的
android:columnCount设为4,让容器将宽度划分为4等份的列空间 - 子Button的
android:layout_columnWeight设为1,使其占据1份空间(即父容器宽度的1/4) - 移除冗余属性:
android:layout_columnSpan="1"(默认就是1)、android:layout_gravity="clip_horizontal"(会影响宽度分配逻辑)
修改后的完整代码:
<GridLayout android:id="@+id/widget_place" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="3" android:layout_marginVertical="10dp" android:orientation="horizontal" android:columnCount="4" android:columnOrderPreserved="false"> <Button android:id="@+id/btn" android:text="card1" android:layout_columnWeight="1" /> </GridLayout>
后续如果在该行添加更多子View,只要给每个子View都设置layout_columnWeight="1",它们会自动均分父容器宽度,每个都占1/4。
内容的提问来源于stack exchange,提问作者Gilad Shoham
相关产品推荐
相关产品推荐

