利用sections创建Android RecyclerViews的一个适配器:SectionedRecyclerView
jopen
9年前
SectionedRecyclerView是一个能够利用sections来创建Android RecyclerViews的适配器。提供headers 和 footers.
用法
In order to use this library, you need to extendSectionedRecyclerView<H, VH, F>where:
- His a class extendingRecyclerView.ViewHolderto hold the view for section headers.
- VHis a class extendingRecyclerView.ViewHolderto hold the view for the regular items in the view.
- Fis a class extendingRecyclerView.ViewHolderto hold the view for section footers.
According to the sample published in this repository:
- 1. Create a class extendingSectionedRecyclerView:
public class CountSectionAdapter extends SectionedRecyclerViewAdapter<CountHeaderViewHolder, CountItemViewHolder, CountFooterViewHolder>
- 2. Implement the corresponding methods:
@Override protected int getItemCountForSection(int section) { return section + 1; } @Override protected int getSectionCount() { return 5; } @Override protected boolean hasFooterInSection(int section) { return true; } protected LayoutInflater getLayoutInflater(){ return LayoutInflater.from(context); } @Override protected CountHeaderViewHolder onCreateSectionHeaderViewHolder(ViewGroup parent, int viewType) { View view = getLayoutInflater().inflate(R.layout.view_count_header, parent, false); return new CountHeaderViewHolder(view); } @Override protected CountFooterViewHolder onCreateSectionFooterViewHolder(ViewGroup parent, int viewType) { View view = getLayoutInflater().inflate(R.layout.view_count_footer, parent, false); return new CountFooterViewHolder(view); } @Override protected CountItemViewHolder onCreateItemViewHolder(ViewGroup parent, int viewType) { View view = getLayoutInflater().inflate(R.layout.view_count_item, parent, false); return new CountItemViewHolder(view); } @Override protected void onBindSectionHeaderViewHolder(CountHeaderViewHolder holder, int section) { holder.render("Section " + (section + 1)); } @Override protected void onBindSectionFooterViewHolder(CountFooterViewHolder holder, int section) { holder.render("Footer " + (section + 1)); } protected int[] colors = new int[]{0xfff44336, 0xff2196f3, 0xff009688, 0xff8bc34a, 0xffff9800}; @Override protected void onBindItemViewHolder(CountItemViewHolder holder, int section, int position) { holder.render(String.valueOf(position + 1), colors[section]); }
3. If you use aGridLayoutManager, you need to set it aSectionedSpanSizeLookupto make sure that headers and footers span the whole width of theRecyclerView:
GridLayoutManager layoutManager = new GridLayoutManager(this, 2); SectionedSpanSizeLookup lookup = new SectionedSpanSizeLookup(adapter, layoutManager); layoutManager.setSpanSizeLookup(lookup); recycler.setLayoutManager(layoutManager);
- 4. Your result will look like this: