2016-07-16 18 views
7

tôi đang sử dụng trình quản lý bố cục ngang cho recyclerView của mình. Tôi cần thực hiện recyclerView theo cách tiếp theo: khi nhấp vào một số mục - làm cho smoothScrool đến vị trí đó và đặt tat item ở trung tâm của recyclerView (nếu có thể, ví dụ 10 mục từ 20).RecyclerView smoothScroll đến vị trí ở giữa. android

vì vậy tôi không có vấn đề với smoothScrollToPosition, nhưng làm thế nào để đặt mục hơn ở trung tâm của RecyclerView ???

cảm ơn!

Trả lời

35

Có nó có thể

By cụ phương pháp RecyclerView.SmoothScroller của '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); 

Đặc biệt trong LinearLayoutManager với 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); 
     } 
    } 
} 

Tốt may mắn

+2

hoàn hảo, nhờ – AnswerZhao

+1

'kéo dài LinearSmoothScroller' phải ghi đè lên 'computeScrollVectorForPosition() ' – Ninja

+0

Làm việc hoàn hảo –

Các vấn đề liên quan