Centering RecyclerView Items Using LinearSnapHelper
Nathan Sokalski
4,111
Reputation points
I have 3 RecyclerView(s) that I want to synchronize & center. I have been able to synchronize them using the following OnScrollListener:
public class PlayerScrollEvent : RecyclerView.OnScrollListener
{
public int ScrollX;
public override void OnScrolled(RecyclerView rv, int dx, int dy)
{
base.OnScrolled(rv, dx, dy);
this.ScrollX += dx;
//System.Diagnostics.Debug.WriteLine($"OnScrolled dx: {dx} ScrollX: {this.ScrollX}");
RecyclerView rvPlayerNames = ((GridLayout)rv.Parent).FindViewById<RecyclerView>(Resource.Id.rvPlayerNames);
RecyclerView rvTotals = ((GridLayout)rv.Parent).FindViewById<RecyclerView>(Resource.Id.rvTotals);
RecyclerView rvScores = ((GridLayout)rv.Parent).FindViewById<RecyclerView>(Resource.Id.rvScores);
rvPlayerNames.ClearOnScrollListeners();
rvTotals.ClearOnScrollListeners();
rvScores.ClearOnScrollListeners();
((LinearLayoutManager)rvPlayerNames.GetLayoutManager()).ScrollToPositionWithOffset(0, -this.ScrollX);
((LinearLayoutManager)rvTotals.GetLayoutManager()).ScrollToPositionWithOffset(0, -this.ScrollX);
((LinearLayoutManager)rvScores.GetLayoutManager()).ScrollToPositionWithOffset(0, -this.ScrollX);
rvPlayerNames.AddOnScrollListener(new PlayerScrollEvent() { ScrollX = this.ScrollX });
rvTotals.AddOnScrollListener(new PlayerScrollEvent() { ScrollX = this.ScrollX });
rvScores.AddOnScrollListener(new PlayerScrollEvent() { ScrollX = this.ScrollX });
}
}
I now need to center them when I use SmoothScrollToPosition. I have found lots of stuff about using LinearSnapHelper to center RecyclerView items, but I have been unable to find any good examples. I am also unsure how my synchronization code will be affected by this.
Developer technologies | .NET | Xamarin
5,381 questions
Sign in to answer