This is the code in which I want to retain recyclerview's scrolled position on orientation change and on activity resume. The problem is in my log, I always get -1. Where am I going wrong?
void resetViews() {
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();
if (lm != null && lm instanceof LinearLayoutManager) {
currPosition = ((LinearLayoutManager)lm).findFirstVisibleItemPosition();
Log.i("saz","curr pos : " + currPosition);
}
int count = lm.getChildCount();
if (currPosition != RecyclerView.NO_POSITION && currPosition < count){
lm.scrollToPosition(currPosition);
}
}
Everything is extremely simple, since you overloaded the adapter, LayoutManager
did not have time to build the elements inside of itself, which means that at the moment all the elements are not visible on the screen. If you even try to call recyclerView.getChildCount()
then you get 0
.
Try something like this:
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
new Handler().postDelayed(new Runnable(){
public void run() {
RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();
if (lm != null && lm instanceof LinearLayoutManager) {
currPosition = ((LinearLayoutManager)lm).findFirstVisibleItemPosition();
Log.i("saz","curr pos : " + currPosition);
}
int count = lm.getChildCount();
if (currPosition != RecyclerView.NO_POSITION && currPosition < count){
lm.scrollToPosition(currPosition);
}
}
}, 500);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With