GridLayoutManager 相同的图像尺寸

tcc*_*288 2 java xml android android-recyclerview

我正在尝试RecyclerViewGridLayoutManager

我最终希望显示与此相同大小的图像,或者如果可能的话甚至是方形的:

在此输入图像描述

GridLayoutManager使这成为可能的要素是什么?我是否修改用于填充的单个项目 XML RecyclerView

小智 6

首先,您必须ImageView像下面这样子类化:

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;


public class MyImageview extends ImageView {
    public MyImageview (Context context) {
        super(context);
    }

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

    public MyImageview (Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
     }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); // Snap to
        // width
    }
}
Run Code Online (Sandbox Code Playgroud)

在 XML 文件中使用此文件。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.app.MyImageview 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/imageBackground"
        android:scaleType="centerCrop"/>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

确保您的MyImageView高度和宽度必须为match_parent