2016-10-05 74 views
2

我有一個回收站視圖,使用LinearSnapHelper來捕捉用戶滾動的項目。現在,我想要聽取快照,最好是獲取已捕捉項目的索引。但是,我無法弄清楚是否有辦法做到這一點。如何找出回收站視圖所捕獲的項目?

最初我以爲LinearSnapHelperfindTargetSnapPosition()會返回索引(如文檔所述),但事實並非如此。它爲第一個項目隨機返回-1或0,當列表滾動時,它將被隨機調用。有時候,這個方法根本不叫;有時,索引是不正確的,有時它是正確的。這似乎沒有用試圖找到索引使用此。

所以:我如何知道回收站視圖捕捉哪個項目?

回答

6

我設法讓這個工作。我不確定這是否是最好的解決方案,但這是我所做的:

private int selectedPosition = -1; 
private LinearLayoutManager layoutManager; 
private RecyclerView recyclerView; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    ... 

    LinearSnapHelper snapHelper = new LinearSnapHelper() { 
     @Override 
     public View findSnapView(RecyclerView.LayoutManager layoutManager) { 
      View view = super.findSnapView(layoutManager); 

      if (view != null) { 
       final int newPosition = layoutManager.getPosition(view); 

       if (newPosition != selectedPosition && recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_IDLE) { 
        onViewSnapped(newPosition); 
        selectedPosition = newPosition; 
       } 

      } 

      return view; 
     } 
    }; 

    ... 
} 

private void onViewSnapped(int index) { 
    // YOUR CODE HERE 
} 
相關問題