You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 08:01:01