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

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

问题描述

我需要添加一个 Activity,我可以在其中列出 ArrayList 的元素,并且我已经看到有一种更新更好的方式来显示列表 -RecyclerView.

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

如果您想知道,我指的是这个我一直在阅读的文档示例.

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

公共类投票扩展活动{RecyclerView myList;私有 ArrayList球员;//玩家@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_voting);意图意图 = this.getIntent();捆绑包 = intent.getExtras();玩家 = (ArrayList)bundle.getSerializable("PLAYERS");myList = (RecyclerView) findViewById(R.id.charactersList);myList.setLayoutManager(new LinearLayoutManager(this));CoursesAdapter 适配器 = new CoursesAdapter(players);myList.setAdapter(适配器);}//或者带有点击监听器的 RecyclerViewCoursesAdapter clickAdapter = new CoursesAdapter(players);clickAdapter.setOnEntryClickListener(new CoursesAdapter.OnEntryClickListener() {@覆盖public void onEntryClick(View view, int position) {//单击列表项时会发生的事情}});recyclerView.setAdapter(clickAdapter);}

所以我认为我把那个 interface 放在了错误的地方(很可能),事实上我已经把它放在了 Adapter 类中,在它的末尾,紧跟在 <代码>onAttachedToRecyclerView() 方法:

 @Override公共无效 onAttachedToRecyclerView(RecyclerView recyclerView) {super.onAttachedToRecyclerView(recyclerView);}私有 OnEntryClickListener mOnEntryClickListener;公共接口 OnEntryClickListener {void onEntryClick(View view, int position);}public void setOnEntryClickListener(OnEntryClickListener onEntryClickListener) {mOnEntryClickListener = onEntryClickListener;}}

解决方案

我记得我第一次阅读 RecyclerViews 的时候 - 我同意一开始可能有点混乱.希望这个解释能帮助你更好地理解它.

<小时>

RecyclerView 基础

1.添加 RecyclerView

首先,您需要将 RecyclerView 添加到您的 XML 布局中.我假设你知道如何做到这一点.您还可以在 Java 代码中声明它:

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

2.创建Adapter并理解ViewHolder

接下来,您需要为其创建一个Adapter.这是一个实现 RecyclerView.Adapter 的类.我将在一分钟内解释这意味着什么.

我相信查看 Adapter 的示例有助于理解它的工作原理(例如 我为开源应用程序创建的).我还强烈建议查看我在 GitHub 上的 Gist 上作为示例制作的一组 Java 文件:

https://gist.github.com/FarbodSalamat-Zadeh/76465721abodSalamat-Zadeh/768ee708c1582c013e1de4f07"/p>

我将在本说明中引用上面链接中的示例文件,以便您可以继续操作.

您可以看到Adapter 类包含一个内部类,也就是您的ViewHolder.因此,它需要扩展RecyclerView.ViewHolder.

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

ExampleViewHolder(View itemView) {超级(项目视图);text1 = (TextView) itemView.findViewById(R.id.text1);text2 = (TextView) itemView.findViewById(R.id.text2);}

这就是 ViewHolder(Adapter 中的内部类)所需的全部内容.

3.理解Adapter

与大多数 Java 对象一样,您将需要在 Adapter 类中具有一些私有变量的构造函数.这是我的:

私有ArrayListmCustomObjects;public ExampleAdapter(ArrayList arrayList) {mCustomObjects = arrayList;}

您需要将 ArrayList 作为构造函数参数,以便您可以传递列表,以便您的 Adapter 可以使用它.

如果您查看 Adapter 类的其余部分,它包含一些方法,它从它扩展的内容中覆盖了这些方法.让我们快速看看这些是什么:

在大多数情况下,getItemCount() 只会返回您的 ArrayListsize().

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

@Override公共 ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {查看视图 = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_2, parent, false);返回新的 ExampleViewHolder(view);}

您可以看到我正在夸大我将用作列表项的布局 (android.R.layout.simple_list_item_2).此布局内置于 Android 中,因此我不需要创建它 - 当然,您可以使用任何您希望的布局,然后针对您可能正在使用的小部件修改您的 Adapter.此方法的返回类型将匹配您为 ViewHolder 内部类命名的任何内容.

现在,有趣的是 onBindViewHolder(...).您可以在此处配置布局,因此您想要做什么完全取决于您.这是您可以使用的模板:

@Overridepublic 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);}

基本上,您可以通过执行 holder.myWidget 访问您的 ViewHolder 变量(用于列表项布局中的小部件).holder 部分来自参数,也就是我们之前谈到的 ViewHolder,而 myWidget 将是 的名称从中查看变量.

在上面的例子中,object 有一个 getFirstText() 方法,而 ViewHolder 包含一个 TextView> (text1),所以我正在设置文本.

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

@Override公共无效 onAttachedToRecyclerView(RecyclerView recyclerView) {super.onAttachedToRecyclerView(recyclerView);}

4.配置 RecyclerView

还记得开始时,我们声明并分配了我们的 RecyclerView 吗?:

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

现在我们要配置它.

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

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

recyclerView.setLayoutManager(new LinearLayoutManager(this));

仅此而已.

接下来我们要做的就是将我们之前创建和自定义的 Adapter 类设置为您的 RecyclerView:

ExampleAdapter adapter = new ExampleAdapter(yourCustomArrayList);recyclerView.setAdapter(适配器);

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

5.使用您的 RecyclerView

上述步骤应该会给你一个有效的 RecyclerView.如果你卡住了,你可以看看我如何在我的应用程序中添加一个 此处.

您还可以查看 Google 示例以了解 RecyclerView 实现.

我希望所有这些都能让您清楚地了解 RecyclerView 的工作原理.

<小时>

添加点击监听器

您可能想要添加一个点击监听器,这样您就不会将 RecyclerView 仅用于显示项目.

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

公共类 ExampleClickViewHolder 扩展 RecyclerView.ViewHolder 实现 View.OnClickListener {TextView text1, text2;ExampleClickViewHolder(View itemView) {超级(项目视图);//我们这样做是因为我们想检查一个项目何时被点击:itemView.setOnClickListener(this);//现在,像以前一样,我们分配我们的 View 变量title = (TextView) itemView.findViewById(R.id.text1);副标题 = (TextView) itemView.findViewById(R.id.text2);}@覆盖public void onClick(View v) {//用户可能没有为列表项设置点击监听器,在这种情况下我们的监听器//将是空的,所以我们需要检查这个如果(mOnEntryClickListener != null){mOnEntryClickListener.onEntryClick(v, getLayoutPosition());}}}

您需要添加的唯一其他内容是 Adapter 的自定义接口和 setter 方法:

私有 OnEntryClickListener mOnEntryClickListener;公共接口 OnEntryClickListener {void onEntryClick(View view, int position);}public void setOnEntryClickListener(OnEntryClickListener onEntryClickListener) {mOnEntryClickListener = onEntryClickListener;}

因此,您的新的、支持点击的 Adapter 已完成.

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

ExampleClickAdapter clickAdapter = new ExampleClickAdapter(yourObjects);clickAdapter.setOnEntryClickListener(new ExampleClickAdapter.OnEntryClickListener() {@覆盖public void onEntryClick(View view, int position) {//单击列表项时会发生的事情}});recyclerView.setAdapter(clickAdapter);

这基本上是设置普通 Adapter 的方式,只是您使用自己创建的 setter 方法来控制用户单击特定列表项时将执行的操作.

<小时>

重申一下,您可以查看我在 GitHub 上的 Gist 上制作的一组示例:

https://gist.github.com/FarbodSalamat-Zadeh/76465728c4104e73e1de4f07/p>

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.

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.

EDIT:

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);
}

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;
}



}

解决方案

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 basics

1. Adding the RecyclerView

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. 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.

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.

You can see that the Adapter class contains an inner class, which is your ViewHolder. Therefore, it needs to extend 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);
}

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

3. Understanding the Adapter

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;
}

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

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() 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)

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

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);
}

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.

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);
}

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.

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

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. Configuring RecyclerView

Remember at the beginning, when we declared and assigned our RecyclerView?:

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

Now we are going to configure it.

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.

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

recyclerView.setLayoutManager(new LinearLayoutManager(this));

That's all.

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.

5. Using your 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.

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

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


Adding a click listener

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

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());
        }
    }
}

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);

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.


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天全站免登陆