如何显示按最喜欢的评论过滤的recyclerview项目?
Posted
技术标签:
【中文标题】如何显示按最喜欢的评论过滤的recyclerview项目?【英文标题】:How to show recyclerview items filtered by most-liked comments? 【发布时间】:2019-12-18 00:40:36 【问题描述】:我想创建一个小型社交应用。我几乎完成了,但我不知道如何在 RecyclerView
中显示评论项,基于最喜欢的那些。
这里是代码
//This is commentAdapter
public void onBindViewHolder(@NonNull final Myholder myHolder, final int i)
final ModelComments modelComments = commentsList.get(i);
String cLikes = commentsList.get(i).getcLikes(); //this is for like
myHolder.user_comment.setText(modelComments.getComment());
myHolder.clickBtn.setText(cLikes);//to show how many likes the user get
//This is commentsActivity
RecyclerView recyclerView;
FirebaseAuth firebaseAuth;
FirebaseUser user;
private CommentAdapter commentAdapter;
private List<ModelComments> commentsList;
recyclerView = findViewById(R.id.comment_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
//show newest comment first and then old
layoutManager.setStackFromEnd(true);
layoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(layoutManager);
commentsList = new ArrayList<>();
commentAdapter= new CommentAdapter(this, commentsList);
recyclerView.setAdapter(commentAdapter);
showAllComment();
private void showAllComment()
try
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("comments");
reference.addValueEventListener(new ValueEventListener()
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
commentsList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren())
ModelComments modelComments = snapshot.getValue(ModelComments.class);
commentsList.add(modelComments);
commentAdapter.notifyDataSetChanged();
@Override
public void onCancelled(@NonNull DatabaseError databaseError)
);
catch (Exception e)
e.printStackTrace();
再一次,有什么办法可以做到这一点?如果您不明白,请在此问题上发表评论。
【问题讨论】:
排序列表然后绑定到适配器 但是怎么绑定呢? 【参考方案1】:如我们所见,您已经通过以下操作完成了绑定
commentsList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren())
ModelComments modelComments = snapshot.getValue(ModelComments.class);
commentsList.add(modelComments);
commentAdapter.notifyDataSetChanged();
首先,您清除了列表,然后添加了 cmets,最后调用了 notifyDataSetChanged。您错过的是在通知数据更改之前对列表进行排序
请查看此链接以了解如何对列表进行排序。 Sort ArrayList of custom Objects by property
【讨论】:
以上是关于如何显示按最喜欢的评论过滤的recyclerview项目?的主要内容,如果未能解决你的问题,请参考以下文章
津市人又可以省一笔钱!湖南高速公路按最短路径收费,持续20天