Android 宽高相等的adapter item内容

版权声明:本文为徐代龙原创文章,未经徐代龙允许不得转载。网络资源网站:xudailong.cc 福利网站:www.00reso.com 公众号:蛇崽网盘教程资源 https://blog.csdn.net/xudailong_blog/article/details/88563211

使用一张网上的图:
在这里插入图片描述
很多时候,我们需要用使用这样的排列,宽高固定,然后是中间留有一定的边距,毫无疑问,这里我们需要用到gridadapter。

GridView的item是正方形,而android需要适配不同尺寸的手机,所以不能写死item的高度和宽度。因为GridView是可以根据numColumns来分配item的宽度的,所以我们把item布局的高度设为与宽度一样就能实现适配了。

(一):所以,在这里,我们自定义一个宽高都相等的RelativeLayout

/**
 * 
 * 高与宽相等的RelativeLayout
 */
 
public class SquareLayout extends RelativeLayout {
    public SquareLayout(Context context) {
        super(context);
    }
 
    public SquareLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    public SquareLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
 
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // For simple implementation, or internal size is always 0.
        // We depend on the container to specify the layout size of
        // our view. We can't really know what it is since we will be
        // adding and removing different arbitrary views and do not
        // want the layout to change as this happens.
        this.setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
        // Children are just made to fill our space.
        int childWidthSize = getMeasuredWidth();
        //设置高度与宽度一样
        heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

(二):在adapter中的item布局进行使用

<?xml version="1.0" encoding="utf-8"?>
<com.demo.viewmine.SquareLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <ImageView
        android:id="@+id/civ"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@mipmap/duck" />
 
</com.demo.viewmine.SquareLayout>

最后效果图就是上面的效果图了,不过你还可以使用这样的布局再多加上一些比较复杂的布局在上面来实现自己自己想要的功能。


关注「蛇崽网盘教程资源」公众号 ,在微信后台回复「领取资源」,获取IT资源200G干货大全。

更多资源请访问:

超详细图文搭建个人免费博客

关注「蛇崽网盘教程资源」公众号 ,在微信后台回复「领取资源」,获取IT资源200G干货大全。

在微信后台回复「130个小程序」,即可免费领取享有导入就能跑的微信小程序

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/xudailong_blog/article/details/88563211
今日推荐