2015-06-29 16 views
23

Tôi muốn một số RecyclerView.LayoutManager cho phép tôi chỉ định số lượng khoảng khác nhau cho các hàng khác nhau làm mẫu lặp lại. Ví dụ 2,3 với 10 mặt hàng sẽ trông như thế này:RecyclerView LayoutManager số lượng khoảng khác nhau trên các hàng khác nhau

------------- 
    |  |  | 
    |  |  | 
    ------------- 
    | | | | 
    | | | | 
    ------------- 
    |  |  | 
    |  |  | 
    ------------- 
    | | | | 
    | | | | 
    ------------- 

tôi có thể nghĩ ra một cách để hack này với GridLayoutManagerSpanSizeLookup nhưng có ai đưa ra một cách sạch hơn để làm điều này?

+0

Mà không phải là được triển khai trong một ['StaggeredGridLayoutManager'?] (https://developer.android.com/reference/android/support/v7/widget/StaggeredGridLayoutManager.html) – user4989692

Trả lời

38

Để thực hiện những gì bạn muốn, bạn có thể phải tự viết LayoutManager của riêng mình.

Tôi nghĩ rằng đây là dễ dàng hơn:

// Create a grid layout with 6 columns 
    // (least common multiple of 2 and 3) 
    GridLayoutManager layoutManager = new GridLayoutManager(this, 6); 

    layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { 
     @Override 
     public int getSpanSize(int position) { 
      // 5 is the sum of items in one repeated section 
      switch (position % 5) { 
      // first two items span 3 columns each 
      case 0: 
      case 1: 
       return 3; 
      // next 3 items span 2 columns each 
      case 2: 
      case 3: 
      case 4: 
       return 2; 
      } 
      throw new IllegalStateException("internal error"); 
     } 
    }); 

Nếu mục lưới của bạn cần phải biết span size của nó, bạn có thể tìm thấy nó như thế này trong vòng ViewHolder:

 // this line can return null when the view hasn't been added to the RecyclerView yet 
     RecyclerView recyclerView = (RecyclerView) itemView.getParent(); 
     GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager(); 
     int spanSize = gridLayoutManager.getSpanSizeLookup().getSpanSize(getLayoutPosition()); 
+0

Đây là một giải pháp tuyệt vời, cảm ơn rất nhiều! –

+0

câu trả lời này dễ dàng hơn http://stackoverflow.com/questions/33696096/setting-span-size-of-single-row-in-staggeredgridlayoutmanager?rq=1 – amorenew

+0

bạn đã cứu cuộc sống của tôi – JiratPasuksmit

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