Home > OS >  After reordering the items in Android recycler view the position is not updating
After reordering the items in Android recycler view the position is not updating

Time:11-20

In my app I am showing a list of buttons in a recycler view, with the help of ItemTouchHelper.SimpleCallback ,onMove function I am able to reorder the buttons but after reordering the position is not updating . For eg:- (If I dragged the button1 from 0 position to 1 position then button1 should show that it's new position is 1 but it is showing old position i.e. 0) Is there any thing that is changing so that I could access it and get to know the new position of my button. Any help would be appreciated.

ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP
                | ItemTouchHelper.DOWN | ItemTouchHelper.START | ItemTouchHelper.END , 0) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
    
                int fromPosition = viewHolder.getAdapterPosition();
                int toPosition = target.getAdapterPosition();
    
                Collections.swap(datalist,fromPosition,toPosition);
    
                recyclerView.getAdapter().notifyItemMoved(fromPosition,toPosition);
                return false;
            }
    
    
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
    
            }
        };

CodePudding user response:

I solved this problem by notifying the entire dats set in the adapater

here is

        Collections.swap(datalist,fromPosition,toPosition);
        recyclerView.getAdapter().notifyItemMoved(fromPosition,toPosition);
        recyclerView.getAdapter().notifyDataSetChanged()
        return false;

CodePudding user response:

This should update the views based on their new position.This is an item change event, not a structural change event. It indicates that any reflection of the data at position is out of date and should be updated.

  recyclerView.getAdapter().notifyDataSetChanged();
  • Related