android GridLayout 设置item间距方式

在创建自定义控件过程中,使用GridLayout布局并动态添加item,发现间距调整困难。尽管官方API缺乏明确的间距设置说明,但通过深入研究,可以实现如图所示的间距效果。本文将探讨解决这个问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

完成一个自定义控件时突发奇想想用gridlayout,动态添加完item之后发现间距不好调整

网上回答类似问题的比较少,找了很久没找到;

Api没有明确描述,看了一会也没找到可调整间距的参数或方法;

我要完成的效果如下图:



于是开始测试,布局里面使用layout_margin
OK,生效(布局里面直接设置layout_margin是生效的,参考代码:
<GridLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:columnCount="6"
        android:orientation="horizontal"
        android:rowCount="5">

        <Button
            android:id="@+id/btn01"
            android:layout_margin="20dp" />

        <Button android:id="@+id/btn02" />

        <Button android:id="@+id/btn03" />
    </GridLayout>
);

然后尝试在代码里面动态添加:
LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(txWidth, txHeight);
  ll.rightMargin = xOffset;
                    ll.topMargin = yOffset / 2;
                    ll.bottomMargin = yOffset / 2;
                    tv.setLayoutParams(ll);
奇怪的事情发生了:并不能生效!!
看了一下源码,豁然开朗:Gridlayout内部的组件不能直接设置LinearLayout.LayoutParams,
否则除了控件大小,其他一概不收,Margin自然也就不生效了;于是改正:
<pre name="code" class="java">                    LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(txWidth, txHeight);
                    GridLayout.LayoutParams gl = new GridLayout.LayoutParams(ll);
                    gl.rightMargin = xOffset;
                    gl.topMargin = yOffset / 2;
                    gl.bottomMargin = yOffset / 2;
                    tv.setLayoutParams(gl);
                    addView(tv);



完美实现效果。



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值