Android GrildView实现每一项等高宽,铺满屏幕

来源:互联网 发布:安恒数据库审计系统 编辑:程序博客网 时间:2024/05/16 10:46

先上效果图:

这里写图片描述

图片是等高宽的,并且会根据不同的屏幕分辨率自动适应。
实现方法:
在grildview中配置以下属性。

android:numColumns="auto_fit"android:columnWidth="100dp"android:stretchMode="columnWidth"

columnWidth只是默认100dp。以上属性的意思是Grildview会根据默认的100dp计算一行能放多少个,多出的部分平均分配给每一项,这样就实现了宽度的自适应。
接下来解决高度:
这里的高度是在item的布局来实现的,思路是自定义一个布局,该布局重新测量实现自身布局的等高宽,然后用该布局来加载item。
这样综合上面:
grildview首先平均分配每一项的宽度,item的布局在绘制加载的时候会根据这个分配的宽度来绘制自身的高宽以实现等高宽。

自定义的布局(就是实现更高宽):

import android.content.Context;import android.util.AttributeSet;import android.widget.LinearLayout;/** * Created by Administrator on 2016/9/14. */public class GrildImgLayout extends LinearLayout {    public GrildImgLayout(Context context) {        super(context);    }    public GrildImgLayout(Context context, AttributeSet attrs) {        super(context, attrs);    }    public GrildImgLayout(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {         setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));        int childWidthSize = getMeasuredWidth();        int childHeightSize = getMeasuredHeight();        //高度和宽度一样        heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }}

用该布局实现item布局:

<?xml version="1.0" encoding="utf-8"?><com.inext.test.admin.ui.customview.GrildImgLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_height="match_parent"    android:layout_width="wrap_content">    <ImageView        android:id="@+id/img"        android:scaleType="fitXY"        android:layout_width="match_parent"        android:layout_height="match_parent">    </ImageView></com.inext.test.admin.ui.customview.GrildImgLayout>

接下来就是像以往那样使用grildview 和 上面的item布局就可以了。

0 0
原创粉丝点击