I created a simple RecyclerView in Java and implemented item click handling in the adapter's onBindViewHolder method with this action that the clicked item moves to position 0.
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
int pos = holder.getBindingAdapterPosition();
ExamItem examItem = examList.get(pos);
holder.examName.setText(examItem.getName());
holder.itemView.setOnClickListener(v -> {
holder.itemView.setBackgroundColor(Color.RED); // just for testing
// Toast.makeText(v.getContext(), "pos: "+pos, Toast.LENGTH_SHORT).show();
if (pos > 0 && pos < getItemCount()) {
examList.remove(pos);
examList.add(0, examItem);
notifyItemMoved(pos, 0);
}
});
}
And this is its implementation:
// Activity or Fragment
private List<ExamItem> ExamItems = new ArrayList<>();
for (int i=0; i<200; i++){
ExamItems.add(new ExamItem("index = "+i));
}
LinearLayoutManager llm = new LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(llm);
RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
itemAnimator.setMoveDuration(250);
recyclerView.setItemAnimator(itemAnimator);
MyAdapter myAdapter = new MyAdapter(ExamItems);
recyclerView.setAdapter(myAdapter);
It almost works but has several issues.
The move animation behaves strangely - it shouldn't change the positions of the next views, but rather the previous views. When calling
notifyItemMoved(from, to), it appears to behave as if it inserts a new item at position 0 (off-screen) and removes the selected item. I expected the previous items to shift down by one position instead.click on the first visible view (not 0 position of recyclerview) is not working. or sometimes it work with strange animation. removing its above items and inserting after the first visible item without any move animation.
Just for testing the click method, I modified the selected item background. It worked but it changes background color of similar items too. For example if 10 items are visible and I click on 3rd item them background of 13, 23, ... items change.
How do I make the moving item appear in front of other items? The default behavior appears to place it behind other items during the animation.

