2016-07-16 81 views
7

我正在爲我的recyclerView使用水平佈局管理器。 我需要用下列方式製作recyclerView:當點擊某件物品時 - 將smoothScrool製作到該位置並將tat物品放在recyclerView的中心(如果可能的話,例如20箇中的10個物品)。RecyclerView smoothScroll放置在中心位置。 android

所以我沒有與smoothScrollToPosition的問題,但如何把項目比在RecyclerView的中心?

謝謝!

回答

35

是有可能

通過工具RecyclerView.SmoothScroller的方法 'onTargetFound'。

/** 
* Called when the target position is laid out. This is the last callback SmoothScroller 
* will receive and it should update the provided {@link Action} to define the scroll 
* details towards the target view. 
* @param targetView The view element which render the target position. 
* @param state   Transient state of RecyclerView 
* @param action  Action instance that you should update to define final scroll action 
*      towards the targetView 
*/ 
abstract protected void onTargetFound(View targetView, State state, Action action); 

特別是在LinearLayoutManager與LinearSmoothScroller

public class CenterLayoutManager extends LinearLayoutManager { 

    public CenterLayoutManager(Context context) { 
     super(context); 
    } 

    public CenterLayoutManager(Context context, int orientation, boolean reverseLayout) { 
     super(context, orientation, reverseLayout); 
    } 

    public CenterLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
     super(context, attrs, defStyleAttr, defStyleRes); 
    } 

    @Override 
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { 
     RecyclerView.SmoothScroller smoothScroller = new CenterSmoothScroller(recyclerView.getContext()); 
     smoothScroller.setTargetPosition(position); 
     startSmoothScroll(smoothScroller); 
    } 

    private static class CenterSmoothScroller extends LinearSmoothScroller { 

     CenterSmoothScroller(Context context) { 
      super(context); 
     } 

     @Override 
     public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) { 
      return (boxStart + (boxEnd - boxStart)/2) - (viewStart + (viewEnd - viewStart)/2); 
     } 
    } 
} 

好幸運

+2

完美,感謝 – AnswerZhao

+1

'延伸LinearSmoothScroller'必須覆蓋'computeScrollVectorForPosition()' – Ninja

+0

曾爲無瑕 –