本文介绍了简单的Android RecyclerView示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Android的RecyclerView列出了一些项目,但这是一个相当复杂的过程.浏览众多在线教程之一(很好),但是我正在寻找一个简单的示例,可以复制并粘贴以快速启动并运行.仅需要以下功能:

I've made a list of items a few times using Android's RecyclerView, but it is a rather complicated process. Going through one of the numerous tutorials online works (this, this, and this are good), but I am looking a bare bones example that I can copy and paste to get up and running quickly. Only the following features are necessary:

  • 垂直布局
  • 每行上只有一个TextView
  • 响应点击事件

由于我曾多次希望这样做,所以我最终决定在下面给出答案,以供将来参考.

Because I have wished for this several times, I finally decided to make the answer below for my future reference and yours.

推荐答案

下面是一个最小的示例,看起来像下面的图像.

The following is a minimal example that will look like the following image.

从一个空的活动开始.您将执行以下任务来添加RecyclerView.您需要做的就是将代码复制并粘贴到每个部分中.稍后,您可以对其进行自定义以满足您的需求.

Start with an empty activity. You will perform the following tasks to add the RecyclerView. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.

  • 将依赖项添加到gradle中
  • 为活动和RecyclerView行添加xml布局文件
  • 制作RecyclerView适配器
  • 在您的活动中初始化RecyclerView

确保以下依赖项位于您的应用程序gradle.build文件中:

Make sure the following dependencies are in your app gradle.build file:

implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'

您可以将版本号更新为最新的.如果您仍在使用Android Studio 2.x,请使用compile而不是implementation.

You can update the version numbers to whatever is the most current. Use compile rather than implementation if you are still using Android Studio 2.x.

RecyclerView添加到您的xml布局中.

Add the RecyclerView to your xml layout.

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/rvAnimals"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

创建行布局

RecyclerView中的每一行只会有一个TextView.创建一个新的布局资源文件.

Create row layout

Each row in our RecyclerView is only going to have a single TextView. Create a new layout resource file.

recyclerview_row.xml

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

    <TextView
        android:id="@+id/tvAnimalName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>

</LinearLayout>

创建适配器

RecyclerView需要一个适配器,才能用您的数据填充每一行中的视图.创建一个新的Java文件.

Create the adapter

The RecyclerView needs an adapter to populate the views in each row with your data. Create a new java file.

MyRecyclerViewAdapter.java

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

    private List<String> mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

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

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

    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData.get(position);
        holder.myTextView.setText(animal);
    }

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


    // 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.tvAnimalName);
            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.get(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);
    }
}

注释

  • 尽管不是绝对必要的,但我包括了用于侦听行上的单击事件的功能.这在旧的ListViews中可用,这是常见的需求.如果不需要,可以删除此代码.
  • Although not strictly necessary, I included the functionality for listening for click events on the rows. This was available in the old ListViews and is a common need. You can remove this code if you don't need it.

将以下代码添加到您的主要活动中.

Add the following code to your main 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
        ArrayList<String> animalNames = new ArrayList<>();
        animalNames.add("Horse");
        animalNames.add("Cow");
        animalNames.add("Camel");
        animalNames.add("Sheep");
        animalNames.add("Goat");

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvAnimals);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MyRecyclerViewAdapter(this, animalNames);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
    }
}

注释

  • 请注意,该活动实现了我们在适配器中定义的ItemClickListener.这使我们能够处理onItemClick中的行单击事件.
  • Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle row click events in onItemClick.

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

That's it. You should be able to run your project now and get something similar to the image at the top.

在行之间添加分隔符

您可以像这样添加一个简单的分隔线

You can add a simple divider like this

DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
    layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);

如果您想要更复杂的东西,请参见以下答案:

If you want something a little more complex, see the following answers:

  • How to add dividers and spaces between items in RecyclerView?
  • How to indent the divider in a linear layout RecyclerView (ie, add padding, margin, or an inset only to the ItemDecoration)

更改点击的行颜色

有关如何更改背景颜色和单击行时添加波纹效果的信息,请参见此答案.

See this answer for how to change the background color and add the Ripple Effect when a row is clicked.

更新行

有关如何添加,删除和更新行的信息,请参见此答案.

See this answer for how to add, remove, and update rows.

  • CodePath
  • YouTube tutorials
  • Android RecyclerView Example (stacktips tutorial)
  • RecyclerView in Android: Tutorial

这篇关于简单的Android RecyclerView示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 01:16