首页 > 解决方案 > 如何使用 GridLayoutManager 自动调整 Recycler View 项目的高度和宽度

问题描述

我正在编写一个日历应用程序,所以我有 28-31 项要显示。

在最坏的情况下,我将有 4 行和 7 列,在最好的情况下,我将有 5 行和 7 列。

我正在使用GridLayoutManager,所以:

recyclerView.layoutManager = GridLayoutManager(context, 7)

我没有使用任何代码来更改适配器中的代码,所以:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DayViewHolder {
    var inflatedView = parent.inflate(R.layout.day_item_row)
    return DayViewHolder(inflatedView)
}

override fun onBindViewHolder(holder: DayViewHolder, position: Int) {
    val day = days[position]
}

我的 xml 参数RecyclerView

   <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/calendarRecycler"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.65"
        android:layout_margin="5dp"/>

对于该项目:

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

    <TextView
        android:id="@+id/dayName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:autoSizeTextType="uniform"
        android:gravity="center"
        android:text="5"/>
</androidx.constraintlayout.widget.ConstraintLayout>

制作物品正方形的最佳方法是什么,将全部自动安装RecyclerView

标签: androidandroid-recyclerviewgrid-layoutgridlayoutmanager

解决方案


为了在 RecyclerView 中有方形元素,请将项目布局(根视图)的父级设置为方形 ViewGroup。在这个例子中,我使用了 FrameLayout,但你可以对任何一个做同样的事情。(相对布局、线性布局等)

public class SquareFrameLayout extends FrameLayout {

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

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

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

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public SquareFrameLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Set a square layout.
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }

}

推荐阅读