Prateek Jain
Prateek Jain

Reputation: 113

RecyclerView Jumps to Top when scrolling through feed

I am working on a Spanish news app, see here:

The problem with the app is that whenever any user clicks on like, play audio or translate button, the recyclerView jumps to top.

Upvotes: 0

Views: 2034

Answers (2)

Aaron
Aaron

Reputation: 3894

Whenever you set a new adapter, RecyclerView removes and detaches the old one. Instead, you could try just updating the data on current adapter, and one simple is to create a public method on your adapter to reassign the data:

public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.FeedViewHolder> {
    // ...
    public void setItems(List<Object> items) {
        mRecyclerViewItems = items;
    }
    // ...
}

Then update your adapter in the onDataChange callback:

@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    mRecyclerViewItems.clear();
    for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
        Model_Feed epiModel = dataSnapshot1.getValue(Model_Feed.class);
        mRecyclerViewItems.add(epiModel);
    }
    if (FeedAdapter != null) {
        FeedAdapter.setItems(mRecyclerViewItems);
        FeedAdapter. notifyDataSetChanged();
    } else {
        FeedAdapter = new FeedAdapter(mView.getContext(), mRecyclerViewItems);
        feedRecycler.setAdapter(FeedAdapter);
    }
}

Upvotes: 2

shriakhilc
shriakhilc

Reputation: 3000

The likely reason is because updating the posts triggers a callback in the ValueEventListener being used to populate the RecyclerView in this line

mUSerCmt.orderByChild("timestamp").addValueEventListener( ... )

Since the view is being cleared and reloaded entirely, it naturally appears as though it has scrolled to the top. There can be multiple approaches to avoid this, and the exact choice will depend upon the update needs of your app. Some that I can think of are:

  1. The best option, though slightly tricky coding wise, would be to use DiffUtil in order to make in place updates (with animations), without clearing the entire list. You should be able to find a number of simple tutorials on how to use the class online.

  2. Use addListenerForSingleValueEvent so that updates to the children do not trigger the clearing of the list. This may be a bad choice, since your app displays news that can change often. However, if the user is switching screens often (to read the news article, for instance), then the refresh will happen enough times and make it less noticeable. Pagination of articles while being fetched would also ensure that the latest batch is up-to-date, while the older ones may have unsynced changes.

The first option is what I'd recommend, but the second one is simpler to code, and can be used to fix issues while gaining some time to properly implement DiffUtil.

Upvotes: 0

Related Questions