首页 > 解决方案 > 如何在运行时更改 RecyclerView 的行数

问题描述

所以我有一个充满图像的回收器视图,我想知道如何使用 android studio 在 Java 运行时更改行数,而不是列数。

因此,如果我正在使用这样的网格布局创建回收站视图:

 recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4, GridLayoutManager.VERTICAL, false));

这意味着我将 RecyclerView 设置为 4 列。

如果这是每个 Recycler 项目的内容。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">


    <ImageView
        android:id="@+id/NewImageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:src="@android:color/transparent"

        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"

        />
</androidx.constraintlayout.widget.ConstraintLayout>

我将如何更改它,例如我可以在一页上有 1 行,或者两行或三行。

我试图这样做


        public FlagDataVHolder(LayoutInflater li, ViewGroup parent, int inNumRows)
        {
            super(li.inflate(R.layout.flag, parent, false));

            newImageView = (ImageView) itemView.findViewById(R.id.newImageView);

            itemView.setOnClickListener(this);

            //Adjust the size of the ViewHolder based on the number of rows
            //Get the screen size
            int screenWidth = parent.getMeasuredWidth();
            int screenHeight = parent.getMeasuredHeight();
            ViewGroup.LayoutParams lp = itemView.getLayoutParams();
            if (inNumRows == 1)
            {
                lp.width = screenWidth;
                lp.height = screenHeight;
            }
            else if (inNumRows == 2)
            {
                lp.width = screenWidth;
                lp.height = screenHeight/2;
            }
            else
            {
                lp.width = screenWidth;
                lp.height = screenHeight/3;
            }
        }

因此,根据行数(可以是 1、2、3),程序会将项目视图大小划分为屏幕大小的分数。

但这不起作用,所以我不知道如何进行。

标签: javaandroidandroid-recyclerview

解决方案


推荐阅读