简体   繁体   中英

How to change selected item position to top in Recyclerview?

I have recyclerview in that I want to change item's position dynamically to top after selecting the item of recyclerview .

Please suggest best way to achieve the above problem?

You need to swap selected item with top item in list, then notify your adapter about position change. A sample code would look like:

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

Hope it helps!

Try this

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 

OR

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

OR

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

add below code in onclick of item,

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

If you have different cases like this , we can achieve this approach from @manohar-reddy and call notifyItemChanged(position) it will also call the onBindViewHolder , then update your layout accordingly.

*In this case, if the 0 item has a different layout from the other items

You might wanna read this reference for getting the item position correctly

thanks to @amit-srivastava answer and @manohar-reddy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM