Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findFirstVisibleItemPosition() of the recyclerview always returns -1

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);
    }
}
like image 700
Sarfaraz Avatar asked Feb 21 '16 19:02

Sarfaraz


1 Answers

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);
like image 138
powerman23rus Avatar answered Oct 02 '22 12:10

powerman23rus