如何在Android中对RecyclerView的项目进行排序。

33

我正在开发一款Android聊天应用程序。当我调用我的API时,它会按用户ID对聊天列表进行排序。但我需要按消息ID序列化,因为我想先显示最后一条消息。以下是我的onBindViewHolder方法,其中我获取值。

public void onBindViewHolder(final MyAdapter_HomeViewHolder holder, final int position) {

    holder.userNameTV.setText(data.get(position).getUserInfo().getFullName());
    holder.msgBodyTV.setText(data.get(position).getBody());
    holder.originator_iD.setText(data.get(position).getUserInfo().getId().toString());

    //message ID. I need to serialize my recyclerView by this ID.biggest id should appear first.
    holder.messageId.setText(data.get(position).getId().toString());

    holder.owner_type_ET.setText("1");
    holder.subject_ET.setText("Message");

}

如果您需要查看完整代码,请访问https://pastebin.com/Zxmq36Gn


2
你是指序列化还是排序?我假设你正在使用RecyclerView,所以你需要做的事情(假设你是指排序)是在添加新项时对列表进行排序,然后在适配器上调用“notifyDataSetChanged()”。这可以通过为RecyclerView中的对象实现比较器函数来完成。请参见此处了解如何排序。 - swerly
1
是的,我的意思是按照message_id进行排序。需要将最大的message_id显示在顶部。而notifyDataSetChanged()像往常一样返回我的user_id。 - Tanvir Durlove
请查看我发布的链接,了解如何对List<Datum>进行排序。在构造函数中,您可以在将其设置为成员变量之前对列表进行排序:`public MyAdapter_home(List<Datum> data, int rowLayout, Context context) { //在此处对数据进行排序 this.data = data; this.rowLayout = rowLayout; this.context = context; }` - swerly
我已经尝试过了,但是没有起作用。希望您能看到我上面提到的完整代码。 - Tanvir Durlove
8个回答

22

在将列表传递给适配器之前,尝试执行以下操作(在 API 调用后、适配器调用 notifydatasetchanged 前):

 Collections.sort(data, new Comparator<CustomData>() {
            @Override
            public int compare(CustomData lhs, CustomData rhs) {
                // -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
                return lhs.getId() > rhs.getId() ? -1 : (lhs.customInt < rhs.customInt ) ? 1 : 0;
            }
        });

代码显示了许多错误。您能否建议一下,根据您的意见,我应该怎么修改代码? - Tanvir Durlove
非常完美。非常感谢。 - Tanvir Durlove
什么是customInt?我有一个id,并通过getId方法获取它。 - Ali Khaki
嗨,阿里,customInt是你用来比较的可比较getter。 - Sanat Chandravanshi
不要使用以下代码:return lhs.getId() > rhs.getId() ? -1 : (lhs.customInt < rhs.customInt ) ? 1 : 0;而是使用以下代码:Integer.compare(rhs.attribute(), lhs.attribute()) - JFouad
如果我们从onChildAdded获取结果,它会干扰onChildChanged的结果。 - DragonFire

5
在 Kotlin 中,加载数据到数组后,可以像这样使用:
myItems.sortWith(Comparator { lhs, rhs ->
            // -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
            if (lhs.name > rhs.name) -1 else if (lhs.id < rhs.id) 1 else 0
        })

之后应用:

myItemAdapter.notifyDataSetChanged()

3
一个更简单的解决方案,适用于那些仍然陷入相同困境的人。
  Collections.sort(data, new Comparator<CustomData>() {
            @Override
            public int compare(CustomData lhs, CustomData rhs) {
                return Integer.compare( rhs.getId(),lhs.getId());
            }
        });

YourAdapter adapter = new YourAdapter(context, data);

//Setup Linear or Grid Layout manager
 recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
 recyclerView.setAdapter(adapter);


2
在传递给RecyclerView Adapter之前,请添加以下代码行。
Collections.sort(yourLists, new Comparator<YourList>() {
        @Override
        public int compare(YourList lhs, YourList rhs) {
            return lhs.getId().compareTo(rhs.getId());
        }
    });

2
在将数据传递给RecyclerView适配器之前。
data.sort(new Comparator<Datum>() {
            @Override
            public int compare(Datum o1, Datum o2) {
                return o1.get(position).getMessageId().compareTo(o2.get(position).getMessageId());
            }
        });

然后将排序后的列表传递(通知)给适配器。

数据排序不起作用。它说API的用法记录为@since 1.8+。 - Tanvir Durlove
请直接使用@Sanat Chandravanshi下面的答案。 - Ramees Thattarath
使用Integer.compare(rhs.attribute(), lhs.attribute())代替return lhs.getId() > rhs.getId() ? -1 : (lhs.customInt < rhs.customInt ) ? 1 : 0; - JFouad

2
 Collections.sort(response.body(), new Comparator<All_posts>() {
                        @Override
                        public int compare(All_posts lhs, All_posts rhs) {
                            if(lhs.getId() > rhs.getId()) {
                                return -1;
                            } else {
                                return 1;
                            }
                        }
                    });
  • "response.body"是我从json中获取的arraylist,这是我传递给recyclerView适配器的内容。

  • "All_posts"是“Model”类,它只包含字段。

  • getId是我想要进行比较的值,它来自于我的model类。

在我设置适配器到recyclerView之前,我写了这段代码。在我将适配器设置到recyclerView之后,我写了recyclerView.getAdapter().notifyDataSetChanged();


0
在将列表传递给适配器之前,请尝试这个。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Collections.sort(yourList, Comparator.comparing(YourModel::getFileSize));
}

0
 List<Items_Detail_model>items_model;
  Collections.sort(items_model, new Comparator<Items_Detail_model>() {
            @Override
            public int compare(Items_Detail_model o1, Items_Detail_model o2) {
                return o1.getDate().compareTo(o2.getDate());
            }
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接