RecyclerView Scroll Index Offset

Nathan Sokalski 4,111 Reputation points
2021-05-05T02:46:41.853+00:00

As we know, ViewHolder(s) for all items in a RecyclerView do not always exist due to the recycling capabilities. Therefore, indexes passed to methods such as GetChildAt are not always in sync with the indexes of the actual items in the Adapter. Although methods such as GetChildAdapterPosition & GetChildLayoutPosition exist, they require me to find the child view to pass to them, which can sometimes be tedious or expensive. Is there any way to simply get the current index offset (due to scrolling) without doing any complex code?

Developer technologies | .NET | Xamarin
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JessieZhang-MSFT 7,716 Reputation points Microsoft External Staff
    2021-05-05T09:33:22.3+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    You can try to store the scroll postion in the OnPause method of the Activity, then get the position and scroll to previouse position in OnResume method.

    public class MainActivity : AppCompatActivity  
    {  
        int lastOffset, lastPosition;  
      
        RecyclerView recyclerView;  
        protected override void OnCreate(Bundle savedInstanceState)  
        {  
            base.OnCreate(savedInstanceState);  
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);  
            SetContentView(Resource.Layout.activity_main);  
      
            recyclerView = FindViewById<RecyclerView>(Resource.Id.recycler);  
            ...  
        }  
      
        protected override void OnPause()  
        {  
            base.OnPause();  
      
            View topView = (recyclerView.GetLayoutManager() as LinearLayoutManager).GetChildAt(0);  
      
            if (topView != null)  
            {  
                lastOffset = topView.Top;  
                lastPosition = (recyclerView.GetLayoutManager() as LinearLayoutManager).GetPosition(topView);  
            }  
        }  
      
        protected override void OnResume()  
        {  
            base.OnResume();  
      
            if ((recyclerView.GetLayoutManager() as LinearLayoutManager) != null && lastPosition > 0)  
            {  
                (recyclerView.GetLayoutManager() as LinearLayoutManager).ScrollToPositionWithOffset(lastPosition, lastOffset);  
            }  
        }  
    }  
    

    Best Regards,

    Jessie Zhang

    ---
    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.