使用带有 GridLayoutManager 的 RecyclerView 的简单 Android 网格示例(类似于旧的 GridView)

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

我知道 RecyclerView 已经取代了旧的 ListViewGridView 的功能。我正在寻找一个非常基本的示例,它显示了使用 RecyclerView 的最小网格设置。我不是在寻找长篇教程风格的解释,只是一个最小的例子。我想象模仿旧 GridView 的最简单的网格将包含以下功能:

简答

对于那些已经熟悉 的人来说,好消息是制作网格大体相同。当您设置 RecyclerView 时,您只需使用 GridLayoutManager 而不是 LinearLayoutManager

recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));

如果您需要更多帮助,请查看以下示例。

完整示例

以下是一个最小示例,如下图所示。

从空 activity 开始。您将执行以下任务来添加 RecyclerView 网格。您需要做的就是复制并粘贴每个部分中的代码。稍后您可以自定义它以满足您的需要。

  • 添加依赖到gradle
  • 为 activity 和网格单元格
  • 添加 xml 布局文件
  • 制作 RecyclerView 适配器
  • 初始化 activity
  • 中的 RecyclerView

更新 Gradle 依赖项

确保以下依赖项在您的应用 gradle.build 文件中:

compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:recyclerview-v7:27.1.1'

您可以将版本号更新为 the most current

创建activity布局

RecyclerView 添加到您的 xml 布局。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvNumbers"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

创建网格单元布局

我们 RecyclerView 网格中的每个单元格只会有一个 TextView。新建布局资源文件。

recyclerview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:padding="5dp"
    android:layout_width="50dp"
    android:layout_height="50dp">

        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:background="@color/colorAccent"/>

</LinearLayout>

创建适配器

RecyclerView 需要一个适配器来用您的数据填充每个单元格中的视图。创建一个新的 java 文件。

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private String[] mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // inflates the cell layout from xml when needed
    @Override
    @NonNull 
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each cell
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.myTextView.setText(mData[position]);
    }

    // total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position
    String getItem(int id) {
        return mData[id];
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

备注

  • 虽然不是绝对必要的,但我包含了用于侦听单元格上的点击事件的功能。这在旧的 GridView 中可用,并且是一种常见的需求。如果不需要,可以删除此代码。

在 Activity

中初始化 RecyclerView

将以下代码添加到您的主activity。

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + adapter.getItem(position) + ", which is at cell position " + position);
    }
}

备注

  • 请注意,activity 实现了我们在适配器中定义的 ItemClickListener。这允许我们处理 onItemClick.
  • 中的单元格点击事件

完成

就是这样。您现在应该可以 运行 您的项目并获得类似于顶部图像的内容。

进行中

圆角

自动调整列

进一步研究

虽然我喜欢并欣赏 ,但我想留下一个注释,因为我发现编码 Adapter (MyRecyclerViewAdapter) 来定义并公开 Listener 方法 onItemClick 不是最好的方法,因为没有正确使用 class 封装。所以我的建议是让 Adapter 单独处理 Listening 操作(这是他的目的!)并将它们与使用 Adapter[=] 的 Activity 分开36=](MainActivity)。这就是我设置适配器的方式 class:

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private String[] mData = new String[0];
    private LayoutInflater mInflater;

    // Data is passed into the constructor
    public MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // Inflates the cell layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    // Binds the data to the textview in each cell
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData[position];
        holder.myTextView.setText(animal);
    }

    // Total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }

    // Stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView myTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            myTextView = (TextView) itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            onItemClick(view, getAdapterPosition());
        }
    }

    // Convenience method for getting data at click position
    public String getItem(int id) {
        return mData[id];
    }

    // Method that executes your code for the action received
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + getItem(position).toString() + ", which is at cell position " + position);
    }
}

请注意现在在 MyRecyclerViewAdapter 中定义的 onItemClick 方法,这是您要为收到的 event/action 编写任务的地方。

为了完成这个转换只需要做一个小改动:Activity 不再需要实现 MyRecyclerViewAdapter.ItemClickListener,因为现在这完全由 适配器 完成。这将是最后的修改:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }
}

您应该将 RecyclerView LayoutManager 设置为网格布局模式。当您想要设置 RecyclerView LayoutManager:

时,只需更改您的代码
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfColumns));

设置在RecyclerView初始化

recyclerView.setLayoutManager(new GridLayoutManager(this, 4));

这是仅来自XML的简单方法

spanCount 列数

layoutManager 使其成为网格或线性(垂直或水平)

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/personListRecyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:spanCount="2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

在您分配回收站视图的 MainActivity 中,只需使用此代码。

recyclerView = findViewById(R.id.recycler_view);
    recyclerView.setHasFixedSize(true);
    //recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setLayoutManager(new GridLayoutManager(this, 2));

如果你想在 xml 文件中的 reyclerview 中设置网格布局,那么你可以将这两个放在 recyclerview xml.

app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount=numberOfItemsInSignleRow

如果您想从 java 代码中设置网格布局,您可以编写此代码。

recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfItemsInSignleRow));
    There are 2 ways to achieve this 
    
    - In Xml
     <androidx.recyclerview.widget.RecyclerView
                            android:id="@+id/list_amenities"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="@dimen/_8sdp"
                            android:nestedScrollingEnabled="false"                 
 app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
                            app:spanCount="2"
app:layout_constraintEnd_toEndOf="@+id/text_parking_lot_amenities"                       app:layout_constraintStart_toStartOf="@+id/text_parking_lot_amenities"                  app:layout_constraintTop_toBottomOf="@id/text_parking_lot_amenities" />

跨度计数用于网格列
- 在 activity

 listAmenities.layoutManager = GridLayoutManager(this, TWO)
 here TWO indicates number of grid columns