android gridview 内容不居中问题
2016-01-28 10:45
363 查看
前两天遇到一个需求,单行gridview要动态添加控件,而控件不足时布局是从左开始的,并不美观,网上并没有找到好方法,作为小白体验了一把自定义控件,因此拿出来给自己以及以后遇到的朋友提供一个思路吧。
代码比较简单,思路就是动态设置padding,移动置视图中间,xml也比较简单写死的数值未做屏幕适配
<pre name="code" class="java"> <span style="white-space:pre"> </span>@Override <span style="white-space:pre"></span>protected void onDraw(Canvas canvas) { <span style="white-space:pre"></span>if (tempChildCount != getChildCount()) { <span style="white-space:pre"></span>LOG.d("childCountChanged old=" + tempChildCount + " new=" + getChildCount()); <span style="white-space:pre"></span>tempChildCount = getChildCount(); <span style="white-space:pre"></span>DisplayMetrics dm = new DisplayMetrics(); <span style="white-space:pre"></span>WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); <span style="white-space:pre"></span>wm.getDefaultDisplay().getMetrics(dm); <span style="white-space:pre"></span>int screenWidth = dm.widthPixels; <span style="white-space:pre"></span>int columnWidth = getColumnWidth(); <span style="white-space:pre"></span>int horizontalSpacing = getHorizontalSpacing(); <span style="white-space:pre"></span>int paddingLeft = (screenWidth - getChildCount() * (columnWidth + horizontalSpacing)) / 2; <span style="white-space:pre"></span>if(paddingLeft<0){//item过多超出屏幕时,左对齐 <span style="white-space:pre"></span>paddingLeft=0; <span style="white-space:pre"></span>} <span style="white-space:pre"></span>LOG.d("paddingLeft =" + paddingLeft); <span style="white-space:pre"></span>setPadding(paddingLeft, getPaddingTop(), getPaddingRight(), getPaddingBottom()); <span style="white-space:pre"></span>} <span style="white-space:pre"></span>super.onDraw(canvas); <span style="white-space:pre"></span>}
代码比较简单,思路就是动态设置padding,移动置视图中间,xml也比较简单写死的数值未做屏幕适配
<......NAVLayout android:id="@+id/id_nav_gridview" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_centerInParent="true" android:layout_gravity="center" android:cacheColorHint="@android:color/transparent" android:clipChildren="true" android:columnWidth="150dip" android:divider="@null" android:dividerHeight="5dip" android:focusable="false" android:gravity="center" android:listSelector="@android:color/transparent" android:numColumns="auto_fit" android:scrollbars="none" android:scrollingCache="false" android:verticalSpacing="2dip" />
int horizontalSpacing = getHorizontalSpacing();
相关文章推荐
- 使用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