Jadav Lalit Jadav Lalit - 2 months ago 28x
Android Question

Recyclerview keep scrolling position after changing layout

I am using recycle view in my application. I have one button above recycle view in relative layout for changing layout manager. It first displays grid layout manager and when a button is clicked it displays Linearlayoutmanager. While I am changing layout manager, recycle view again starts from the first position.

Can anyone help me to keep the position as it is when making the change in layout manager dynamically?


You have to remember the firstVisibleItem and scroll to that position after changing the LayoutManager it works fine I just tried it out by myself:

E.g. Button click to change LayoutManager:

btn.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
               int i = ((LinearLayoutManager) rcView.getLayoutManager()).findFirstVisibleItemPosition();
               if(rcView.getLayoutManager() instanceof GridLayoutManager) {                  
                   rcView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
               } else {                     
                   rcView.setLayoutManager(new GridLayoutManager(MainActivity.this, 3));