如何在RecyclerView中显示ArrayList? [英] How to display an ArrayList in a RecyclerView?

查看:206
本文介绍了如何在RecyclerView中显示ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要添加一个活动,其中我可以列出 ArrayList< CustomClass> 和I'的元素我们看到有更新更好的方式来显示列表 - RecyclerView

I need to add an Activity where I can list the elements of an ArrayList<CustomClass> and I've seen there's a newer and better way to display lists - RecyclerView.

我的问题是如何将其实现为我的应用。
我发现我需要使用 Adapter ,但我不太明白如何正确实现整个过程。

My question is how to implement this into my app. I've found that I need to use an Adapter, but I don't quite understand how to implement the whole process correctly.

如果你想知道,我指的是这个文档的例子,我一直在阅读。

If you're wondering, I'm referring to this examples of the docs, which I have been reading.

编辑:

之后更新了我的代码,它说它无法解析符号 setOnEntryClickListener

After having updated my code, it says it cannot resolve the symbol setOnEntryClickListener:

public class voting extends Activity {


RecyclerView myList;
private ArrayList<Player> players; // Players


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

    Intent intent = this.getIntent();
    Bundle bundle = intent.getExtras();
    players = (ArrayList<Player>)bundle.getSerializable("PLAYERS");

    myList = (RecyclerView) findViewById(R.id.charactersList);
    myList.setLayoutManager(new LinearLayoutManager(this));
    CoursesAdapter adapter = new CoursesAdapter(players);
    myList.setAdapter(adapter);
}

// OR RecyclerView with a click listener

CoursesAdapter clickAdapter = new CoursesAdapter(players);
clickAdapter.setOnEntryClickListener(new CoursesAdapter.OnEntryClickListener() {
    @Override
    public void onEntryClick(View view, int position) {
        // stuff that will happen when a list item is clicked
    }
});
recyclerView.setAdapter(clickAdapter);
}

所以我认为我已经把那个界面在错误的地方(非常可能),事实上我把它放在Adapter类中,在它的末尾,就在 onAttachedToRecyclerView()方法:

So I've thought I had put that interface in the wrong place (very probably), infact I've put it in the Adapter class, at the end of it, right after the onAttachedToRecyclerView() Method:

    @Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}


private OnEntryClickListener mOnEntryClickListener;

public interface OnEntryClickListener {
    void onEntryClick(View view, int position);
}

public void setOnEntryClickListener(OnEntryClickListener onEntryClickListener) {
    mOnEntryClickListener = onEntryClickListener;
}



}


推荐答案

我记得当我第一次读到 RecyclerView 时 - 我同意它起初可能有点令人困惑。希望这个解释能帮助你更好地理解它。

I remember when I was first reading about RecyclerViews - I agree it can be a little confusing at first. Hopefully, this explanation will help you understand it better.

首先,您需要添加 RecyclerView 到您的XML布局。我假设你知道怎么做。您还在Java代码中声明它:

First you need to add your RecyclerView to your XML layout. I'm assuming you know how to do this. You also declare it in your Java code:

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.your_recycler_view);



2。创建适配器并理解 ViewHolder



接下来,你需要为它创建 适配器 。这是一个实现 RecyclerView.Adapter< YourAdapter.YourViewHolder> 的类。我将在一分钟内解释这意味着什么。

2. Creating the Adapter and understanding ViewHolder

Next, you need to create an Adapter for it. This is a class that implements RecyclerView.Adapter<YourAdapter.YourViewHolder>. I will explain what this means in a minute.

我认为查看适配器的示例会有所帮助要了解它是如何工作(如的我为开源应用创建了一个。我还强烈建议查看我在GitHub上作为示例的一组Java文件:

I believe it helps to look at an example of an Adapter to understand how it works (e.g. one I created for an open-source app). I would also highly recommend looking through a set of Java files I have made as an example on Gist on GitHub:

https://gist.github.com/FarbodSalamat-Zadeh/7646564f48ee708c1582c013e1de4f07

我将在此解释中引用上面链接中的示例文件,以便您可以继续。

I will be referencing the example files from the link above in this explanation so you can follow along.

您可以看到适配器 class包含一个内部类,它是你的 ViewHolder 。因此,它需要扩展 RecyclerView.ViewHolder

You can see that the Adapter class contains an inner class, which is your ViewHolder. Therefore, it needs to extend RecyclerView.ViewHolder.

在此 ViewHolder ,您声明将用于 RecyclerView 中每个列表项的布局变量。在 ViewHolder 的构造函数中,您可以分配这些变量。我指的是代码的这一部分(我在下面给出我的例子):

Inside this ViewHolder, you declare the variables for the layouts that will be used for each list item in your RecyclerView. In the constructor for your ViewHolder, you assign these variables. I'm referring to this part of the code (I'm giving my example below):

    ExampleViewHolder(View itemView) {
        super(itemView);
        text1 = (TextView) itemView.findViewById(R.id.text1);
        text2 = (TextView) itemView.findViewById(R.id.text2);
    }

这就是你需要的 ViewHolder 适配器中的内部类)。

That's all you need for your ViewHolder (the inner class in your Adapter).

与大多数Java对象一样,您需要在<$中使用构造函数一些私有变量c $ c>适配器类。这是我的:

Like most Java objects, you will need to have a constructor some private variables in your Adapter class. Here are mine:

private ArrayList<CustomClass> mCustomObjects;

public ExampleAdapter(ArrayList<CustomClass> arrayList) {
    mCustomObjects = arrayList;
}

您需要拥有 ArrayList< CustomClass> 作为构造函数参数,因此您可以传递列表,以便适配器可以使用它。

You will need to have your ArrayList<CustomClass> as a constructor parameter so you can pass the list so your Adapter can use it.

如果你看一下 Adapter 类的其余部分,它会包含一些从它扩展的内容覆盖的方法。让我们快速看看它们是什么:

If you look at the rest of the Adapter class, it contains some methods which it overrides from what it extends. Let's have a quick look at what these are:


  • getItemCount()返回您的清单大小。

  • onCreateViewHolder(...)用于为列表项目的布局进行通货膨胀。

  • onBindViewHolder(...)配置列表项的布局(例如,将文本设置为 TextView

  • getItemCount() returns the size of your list.
  • onCreateViewHolder(...) is used to inflate the layout for your list item.
  • onBindViewHolder(...) configures your layouts for the list item (e.g. setting text to a TextView)

对于大多数情况, getItemCount()将只返回您的 ArrayList< CustomClass> size()

For most cases, getItemCount() will just return the size() of your ArrayList<CustomClass>.

onCreateViewHolder(...)方法通常也保持不变:

The onCreateViewHolder(...) method generally stays the same too:

@Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_2, parent, false);
    return new ExampleViewHolder(view);
}

你可以看到我正在膨胀我将用作列表的布局item( android.R.layout.simple_list_item_2 )。这个布局内置于Android中,因此我不需要创建它 - 当然,您可以使用您希望的任何布局,然后修改您的适配器以获取您可能使用的小部件正在使用。此方法的返回类型将匹配您命名为 ViewHolder 内部类的任何内容。

You can see that I am inflating the layout that I will use as my list item (android.R.layout.simple_list_item_2). This layout is built in to Android so I don't need to create it - of course, your can use whatever layout you wish and then modify your Adapter for widgets that you may be using. The return type of this method will match whatever you named your ViewHolder inner class.

现在,有趣的是在 onBindViewHolder(...)。您可以在此处配置布局,因此完全取决于您要执行的操作。这是你可以使用的模板:

Now, the interesting bit is in onBindViewHolder(...). You configure your layouts here, so it is completely up to you what you want to do. Here's a template you could use:

@Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
    CustomClass object = mCustomObjects.get(position);

    String firstText = object.getFirstText()
    String secondText = object.getSecondText()

    holder.text1.setText(firstText);
    holder.text2.setText(secondText);
}

基本上,您可以访问 ViewHolder holder.myWidget ,$ c>变量(对于列表项布局中的小部件)。 holder 部分来自参数,这是我们之前讨论过的 ViewHolder myWidget 将是 View 变量的名称。

Basically, you access your ViewHolder variables (for the widgets in your list item layout) by doing holder.myWidget. The holder part is coming from the parameter, which is your ViewHolder we talked about earlier, and myWidget would be the name of the View variable from that.

在上面的例子,对象有一个 getFirstText()方法,以及 ViewHolder 包含 TextView text1 ),所以我正在设置文本。

In the example above, the object has a getFirstText() method, and the ViewHolder contains a TextView (text1), so I am setting the text.

还有一种方法 - onAttachedToRecyclerView(...)。您可以将它用于更复杂的事情,但在基本层面上,通常是:

There is also one more method - onAttachedToRecyclerView(...). You can use this for more complex things, but at a basic level, it is usually this:

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}



4。配置 RecyclerView



请记住,当我们声明并分配我们的 RecyclerView ?:

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.your_recycler_view);

现在我们要配置它。

首先设置布局管理器。这决定了每个列表项在屏幕上的显示方式。常见的是 LinearLayoutManager GridLayoutManager 。前者将您的列表项放入标准列表(没有什么特别的,但它非常有用),后者将列表项组织成网格类型的布局。

You start by setting a "layout manager". This determines how each list item will be displayed on screen. The common ones are LinearLayoutManager and GridLayoutManager. The former puts your list items into a standard list (nothing special really, but it is very useful), and the latter organises your list items into a grid type of layout.

在我们的示例中,我们将使用 LinearLayoutManager 。要在 RecyclerView 上设置它,我们这样做:

In our example, we're going to use a LinearLayoutManager. To set this on the RecyclerView, we do this:

recyclerView.setLayoutManager(new LinearLayoutManager(this));

这就是全部。

我们所有人接下来要做的就是设置我们之前创建的 Adapter 类,并在 RecyclerView 中自定义:

And all we have to do next is to set the Adapter class we created and customised earlier to your RecyclerView:

ExampleAdapter adapter = new ExampleAdapter(yourCustomArrayList);
recyclerView.setAdapter(adapter);

在上面,我假设您的适配器只有一个参数,但这取决于你之前的配置方式。

In the above, I'm assuming your adapter only has one parameter, but this will depend on how you configured it earlier.

上面的步骤可以让你有一个工作 RecyclerView 。如果你遇到困难,你可以看看我是如何在我的应用程序中添加一个这里

The steps above should give you a working RecyclerView. If you get stuck, you can look at how I added one into my app here.

您还可以查看 Google样本用于 RecyclerView 实施

You can also look through the Google samples for the RecyclerView implementation.

我希望所有这些都让你清楚了解 RecyclerView 的工作原理。

I hope all of this gave you a clear idea about how RecyclerView works.

您可能想要添加点击监听器,以便不使用 RecyclerView 仅用于显示项目。

You may want to add a click listener so that you are not using the RecyclerView just for displaying items.

为此,您的内部 ViewHolder 类需要实现 View.OnClickListener 。这是因为您将 OnClickListener 设置为 ViewHolder itemView 参数c $ c>的构造函数。让我告诉你我的意思:

To do this, your inner ViewHolder class needs to implement View.OnClickListener. This is because you will set an OnClickListener to the itemView parameter of the ViewHolder's constructor. Let me show you what I mean:

public class ExampleClickViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    TextView text1, text2;

    ExampleClickViewHolder(View itemView) {
        super(itemView);

        // we do this because we want to check when an item has been clicked:
        itemView.setOnClickListener(this);

        // now, like before, we assign our View variables
        title = (TextView) itemView.findViewById(R.id.text1);
        subtitle = (TextView) itemView.findViewById(R.id.text2);
    }

    @Override
    public void onClick(View v) {
        // The user may not set a click listener for list items, in which case our listener
        // will be null, so we need to check for this
        if (mOnEntryClickListener != null) {
            mOnEntryClickListener.onEntryClick(v, getLayoutPosition());
        }
    }
}

您需要的其他唯一的东西添加是适配器的自定义界面和setter方法:

The only other things you need to add are a custom interface for your Adapter and a setter method:

private OnEntryClickListener mOnEntryClickListener;

public interface OnEntryClickListener {
    void onEntryClick(View view, int position);
}

public void setOnEntryClickListener(OnEntryClickListener onEntryClickListener) {
    mOnEntryClickListener = onEntryClickListener;
}

所以你的新点击支持适配器已完成。

So your new, click-supporting Adapter is complete.

现在,让我们使用它......

Now, let's use it...

    ExampleClickAdapter clickAdapter = new ExampleClickAdapter(yourObjects);
    clickAdapter.setOnEntryClickListener(new ExampleClickAdapter.OnEntryClickListener() {
        @Override
        public void onEntryClick(View view, int position) {
            // stuff that will happen when a list item is clicked
        }
    });
    recyclerView.setAdapter(clickAdapter);

基本上你将如何设置一个普通的适配器,除了您使用您创建的setter方法来控制用户点击特定列表项时您将执行的操作。

It's basically how you would set up a normal Adapter, except that you use your setter method that you created to control what you will do when your user clicks a particular list item.

重申一下,你可以看看我在GitHub上对这个Gist做的一组例子:

To reiterate, you can look through a set of examples I made on this Gist on GitHub:

https://gist.github.com/FarbodSalamat-Zadeh/7646564f48ee708c1582c013e1de4f07

这篇关于如何在RecyclerView中显示ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆