您的位置:首页 > 移动开发 > Android开发

android gridview 内容不居中问题

2016-01-28 10:45 363 查看
前两天遇到一个需求,单行gridview要动态添加控件,而控件不足时布局是从左开始的,并不美观,网上并没有找到好方法,作为小白体验了一把自定义控件,因此拿出来给自己以及以后遇到的朋友提供一个思路吧。

<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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android gridview canvas