如何在Recyclerview中将所选项目位置更改为顶部?

问题描述 投票:1回答:4

我有recyclerview,因为我想在选择recyclerview项目后动态地将项目的位置更改为top。

请建议实现上述问题的最佳方法?

android android-recyclerview recycler-adapter
4个回答
8
投票

您需要将所选项目与列表中的顶部项目交换,然后通知适配器有关位置更改的信息。示例代码如下所示:

Collections.swap(orderItems.getItems(), position, 0);
                notifyItemMoved(position, 0);

希望能帮助到你!


5
投票

试试这个

String Item = List.get(position); 
List.remove(position);  // remove item from the list
List.add(0,removedItem); // add at 0 index of your list
notifyDataSetChanged();
linearLayoutManager.scrollToPositionWithOffset(0, 20); // scroll recyclerview to top 

要么

recyclerview.getLayoutManager().scrollToPosition(0)  // scroll recyclerview to top 

要么

recyclerview.smoothScrollToPosition(0);  // scroll recyclerview to top 

2
投票

在项目的onclick中添加以下代码,

String removedItem = actualList.remove(position); 
//actualList is list used to populate recylerview and position is selected 
//item position
actualList.add(0,removedItem);
notifyDataSetChanged();

0
投票

如果你有不同的cases like this,我们可以从@manohar-reddy实现这种方法并调用notifyItemChanged(position)它也会调用onBindViewHolder,然后相应地更新你的布局。

*在这种情况下,如果0项目的布局与其他项目不同

您可能想阅读this reference以正确获取项目位置

感谢@ amit-srivastava的回答和@ manohar-reddy

© www.soinside.com 2019 - 2024. All rights reserved.