android GridLayout 设置item间距方式

来源:互联网 发布:枪与玫瑰乐队知乎 编辑:程序博客网 时间:2024/06/11 13:40

完成一个自定义控件时突发奇想想用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 0
原创粉丝点击