Horizontally center first item of RecyclerView

前端 未结 4 1284
孤城傲影
孤城傲影 2020-12-14 23:12

I want to use a RecyclerView to emulate the behavior of a MultiViewPager, in particular I\'d like to have the selected item at the center of the sc

4条回答
  •  自闭症患者
    2020-12-14 23:44

    An improvement on @I.S answer which works 100% of the time and is very easy to implement without any glitchy animation. First we have to use PagerSnapHelper() to have view pager like scroll. To center the items you need to add a large padding on the recyclerView and then clip to the padding. Then use a customized LinearSmoothScroller to smoothly center your item. To center the item on load, just use smooth scroll to position 0. Below is the code

    
    

    And in Code (in C#)

    RecyclerView.LayoutManager lm = new LinearLayoutManager(Context, LinearLayoutManager.Horizontal, false);
    
    recycler_selection = view.FindViewById(Resource.Id.recycler_selection);
    recycler_selection.SetLayoutManager(new LinearLayoutManager(Context, LinearLayoutManager.Horizontal, false));
    // 
    
    RecyclerView.SmoothScroller smoothScroller = new CenterScroller(recycler_selection.Context);
    
    SnapHelper helper = new PagerSnapHelper();
    helper.AttachToRecyclerView(recycler_selection);
    
    smoothScroller.TargetPosition = 0;
    lm.StartSmoothScroll(smoothScroller);
    
    public class CenterScroller : LinearSmoothScroller
        {
            float MILLISECONDS_PER_INCH = 350f;
    
            public CenterScroller(Context context) : base(context)
            {
            }
    
            public override int CalculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference)
            {
                return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2);
            }
    
            protected override float CalculateSpeedPerPixel(DisplayMetrics displayMetrics)
            {
                return MILLISECONDS_PER_INCH / displayMetrics.Xdpi;
            }
        }
    

提交回复
热议问题