我有recyclerview
,因为我想在选择recyclerview
项目后动态地将项目的位置更改为top。
请建议实现上述问题的最佳方法?
您需要将所选项目与列表中的顶部项目交换,然后通知适配器有关位置更改的信息。示例代码如下所示:
Collections.swap(orderItems.getItems(), position, 0);
notifyItemMoved(position, 0);
希望能帮助到你!
试试这个
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
在项目的onclick中添加以下代码,
String removedItem = actualList.remove(position);
//actualList is list used to populate recylerview and position is selected
//item position
actualList.add(0,removedItem);
notifyDataSetChanged();
如果你有不同的cases like this,我们可以从@manohar-reddy实现这种方法并调用notifyItemChanged(position)
它也会调用onBindViewHolder
,然后相应地更新你的布局。
*在这种情况下,如果0项目的布局与其他项目不同
您可能想阅读this reference以正确获取项目位置
感谢@ amit-srivastava的回答和@ manohar-reddy