0

我已經成功實現RecyclerView使用GirdLayoutManager(普通實現,沒有什麼特別),但現在我卡住了,因爲我想在前3個元素後添加自定義視圖/行。 查看圖像下方(藍色區域):使用GridLayoutManager自定義視圖/行在RecyclerView

enter image description here

我怎樣才能做到這一點?有任何想法嗎?謝謝!

+0

檢查這個https://guides.codepath.com/android/Heterogenous-Layouts -inside-RecyclerView –

回答

2

設置你的網格佈局管理器象下面這樣:

final GridLayoutManager mng_layout = new GridLayoutManager(this.getActivity(), 2); 

mng_layout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { 
      @Override 
      public int getSpanSize(int position) { 
       switch(recyclerAdapter.getItemViewType(position)) { 
        case MyRecyclerAdapter.TYPE_SINGLE: 
         return 1; 
        case MyRecyclerAdapter.TYPE_DEFAULT: 
         return 2; 
        default: 
         return -1; 
       } 
      } 
     }); 
myRecyclerView.setLayoutManager(mng_layout); 

,然後更新您的RecyclerViewAdapter如下:

@Override 
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
    View view = null; 
    if (viewType==TYPE_DEFAULT) { 
     View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_grid_view_item, parent, false); 
     return new DefaultViewHolder(view); 
    } else if (viewType==TYPE_SINGLE){ 
     View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_grid_view_header, parent, false); 
     return new SingleItemViewHolder(view); 
    } 
    throw new RuntimeException("There is no type that matches the type " + viewType + " + make sure your using types correctly"); 
} 

@Override 
public int getItemViewType(int position) { 
    return (list.get(position).getType()==TYPE_DEFAULT) ? TYPE_DEFAULT : TYPE_SINGLE; 
} 
+0

它的工作原理!這種簡單的解決方案。謝謝<3 – Ziga

+0

高興地幫助你。請接受它爲正確答案。在投票箭頭下方勾選圖標。 – nnn

相關問題