2015-10-09 54 views
2

我有一個水平回收站視圖,我想在其中啓用對齊。我閱讀了SO上的一些線程,發現this代碼工作得很好。我沒有關於回收器查看和佈局管理器內部運作方面的知識,以便想問問,如果可以把代碼修改爲:在水平回收站視圖中對齊

  1. 無論一扔的速度,我只想移動一個什麼項目向前或向後。

  2. 捕捉速度很慢。如果我移動視圖的寬度超過一半,那麼下一個項目會進入中心但非常緩慢。這可以增加,以便瞬間捕捉?

有關如何實現上述行爲的任何想法將非常有幫助。

回答

2

最後與從其他代碼一些幫助想通了:

public class FlingRecyclerView extends RecyclerView { 

    int screenWidth; 

    public FlingRecyclerView(Context context) { 
     super(context); 
     WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); 
     Display display = windowManager.getDefaultDisplay(); 
     Point size = new Point(); 
     display.getSize(size); 
     screenWidth = size.x; 
    } 

    public FlingRecyclerView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); 
     Display display = windowManager.getDefaultDisplay(); 
     Point size = new Point(); 
     display.getSize(size); 
     screenWidth = size.x; 
    } 

    public FlingRecyclerView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); 
     Display display = windowManager.getDefaultDisplay(); 
     Point size = new Point(); 
     display.getSize(size); 
     screenWidth = size.x; 
    } 

    @Override 
    public boolean fling(int velocityX, int velocityY) { 
     LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager(); 

//these four variables identify the views you see on screen. 
     int lastVisibleView = linearLayoutManager.findLastVisibleItemPosition(); 
     int firstVisibleView = linearLayoutManager.findFirstVisibleItemPosition(); 
     View firstView = linearLayoutManager.findViewByPosition(firstVisibleView); 
     View lastView = linearLayoutManager.findViewByPosition(lastVisibleView); 

//these variables get the distance you need to scroll in order to center your views. 
//my views have variable sizes, so I need to calculate side margins separately. 
//note the subtle difference in how right and left margins are calculated, as well as 
//the resulting scroll distances. 


     int leftMargin = (screenWidth - lastView.getWidth())/2; 
     int rightMargin = (screenWidth - firstView.getWidth())/2 + firstView.getWidth(); 
     int leftEdge = lastView.getLeft(); 
     int rightEdge = firstView.getRight(); 
     int scrollDistanceLeft = leftEdge - leftMargin; 
     int scrollDistanceRight = rightMargin - rightEdge; 

//if(user swipes to the left) 
     if (velocityX > 0) smoothScrollBy(scrollDistanceLeft, 0); 
     else smoothScrollBy(-scrollDistanceRight, 0); 

     return true; 
    } 
} 

工作真棒對我的要求。希望它也能幫助別人。