GridView 完美填充布局

在做项目时,有时候GridView的item和item之间的间距,间隔不好调节,显示在界面上很难看,下面来看如何实现的

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <GridView
        android:id="@+id/main_gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        android:padding="5dp"
        android:gravity="center"
        android:numColumns="5"
        android:stretchMode="columnWidth"
        android:horizontalSpacing="3dp"
        android:verticalSpacing="3dp" />

</LinearLayout>

gridview_item布局

<com.MyRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/main_gridView_item_photo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:contentDescription="@null"
        android:scaleType="centerCrop"
        android:src="@drawable/empty_photo"
        android:layout_centerInParent="true" />

</com.MyRelativeLayout>

MyRelativeLayout.java类

/**
 * 正方形的RelativeLayout
 *
 */
public class MyRelativeLayout extends RelativeLayout {
    public MyRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyRelativeLayout(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
      
        setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));

        // Children are just made to fill our space.
        int childWidthSize = getMeasuredWidth();
        //高度和宽度一样
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
        heightMeasureSpec = widthMeasureSpec;
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}


猜你喜欢

转载自blog.csdn.net/u014120638/article/details/45673169