android GridLayout 设置item间距方式
2015-10-30 11:53
477 查看
完成一个自定义控件时突发奇想想用gridlayout,动态添加完item之后发现间距不好调整
网上回答类似问题的比较少,找了很久没找到;
Api没有明确描述,看了一会也没找到可调整间距的参数或方法;
我要完成的效果如下图:
![](https://img-blog.csdn.net/20151030114244349?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
于是开始测试,布局里面使用layout_margin
OK,生效(布局里面直接设置layout_margin是生效的,参考代码:
然后尝试在代码里面动态添加:
看了一下源码,豁然开朗:Gridlayout内部的组件不能直接设置LinearLayout.LayoutParams,
否则除了控件大小,其他一概不收,Margin自然也就不生效了;于是改正:
完美实现效果。
网上回答类似问题的比较少,找了很久没找到;
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);
完美实现效果。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories