How to make RecyclerView's grid item to have equal height and width?

会有一股神秘感。 提交于 2019-12-05 02:39:11

One way you can ensure equal width/height is to use a custom view which calculates the height based on its width when onMeasure() is called. The neat thing with this is that other than creating the custom view, there's no coding involved.

Here's a custom view extending LinearLayout:

public class SquareLayout extends LinearLayout {

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

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

    public SquareLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int width, int height) {
        // note we are applying the width value as the height
        super.onMeasure(width, width);
    }

}

Here's an altered version of your grid item layout, using the above custom LinearLayout:

<com.yourpackage.name.views.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/profile_picture"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:cropToPadding="false"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:includeFontPadding="false"
        android:textColor="@android:color/black"
        android:text="Theodore"/>

</com.yourpackage.name.views.SquareLayout>

I've done this using ConstraintLayout:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        tools:src="@drawable/ic_chat_bubble_black_24dp"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

You may write code in "onBindViewHolder" function in recycler view holder. In that you can get view tree observer of recycler view and change width or(and) height of recycler item view.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!