I use a RecyclerView
in Android that lists the items in reverse order meaning that the item that has been inserted at last, is at the top of the recyclerview. The problem is when navigating to the Fragment that hosts the RecyclerView, the RecyclerView
shows the item on the very bottom
such that I have to scroll up to see the first item (which is the one that has been inserted last).
I would like the RecylcerView
to show the top of it when I navigate to the Fragment that hosts the RecyclerView such that the last inserted item is shown. I tried 2 approaches that are suggested here Scroll RecyclerView to show selected item on top by using recyclerview.scrollToPosition(position)
which does not have any effect and linearLayoutManager.scrollToPositionWithOffset(2, 20);
which leads to the error message
Cannot resolve method
scrollToPositionWithOffset
inLayoutManager
.
Here is the part of the code for building the recylerview:
public void buildRecyclerView () {
myItemsRecyclerView = binding.recyclerView;
myItemsRecyclerView.setHasFixedSize(true);
myItemsLayoutManager = new LinearLayoutManager(this.getContext(),LinearLayoutManager.VERTICAL, true);
adapterRVMyItems = new Adapter_RV_MyItems(myItemsList);
myItemsRecyclerView.setLayoutManager(myItemsLayoutManager);
mItemsRecyclerView.setAdapter(adapterRVMyItems);
myItemsRecyclerView.scrollToPosition(0); //Does not have any effects
//myItemsLayoutManager.scrollToPositionWithOffset(0, 0); //Error: Cannot resolve method 'scrollToPositionWithOffset' in 'LayoutManager'
Any idea why the solutions suggested in the other thread are not working or what else I can do in order to let the Fragment display the top of the recylerView?
CodePudding user response:
You can use this:
Collections.reverse(myItemsList);
Or you can use:
Collections.sort(myItemsList, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
PojoCLass u1 = (PojoCLass ) o1;
PojoCLass u2 = (PojoCLass ) o2;
return u1.getCreatedAt.compareToIgnoreCase(u2.getCreatedAt());
}
});