You can use this class to realize a simple sectioned RecyclerView.Adapter
without changing your code.
The RecyclerView
should use a LinearLayoutManager
.
You can use this code also with the TwoWayView
with the ListLayoutManager
(https://github.com/lucasr/twoway-view)
This is a porting of the class SimpleSectionedListAdapter
provided by Google
Example:
//Your RecyclerView
mRecyclerView = (RecyclerView) findViewById(R.id.list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addItemDecoration(new DividerItemDecoration(this,LinearLayoutManager.VERTICAL));
//Your RecyclerView.Adapter
mAdapter = new SimpleAdapter(this,sCheeseStrings);
//This is the code to provide a sectioned list
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();
//Sections
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0,"Section 1"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(5,"Section 2"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(12,"Section 3"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(14,"Section 4"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(20,"Section 5"));
//Add your adapter to the sectionAdapter
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
SimpleSectionedRecyclerViewAdapter(this,R.layout.section,R.id.section_text,mAdapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
//Apply this adapter to the RecyclerView
mRecyclerView.setAdapter(mSectionedAdapter);
You can customize the section layout, changing the layout section.xml and changing the code in the SimpleSectionedRecyclerViewAdapter.SectionViewHolder
class and SimpleSectionedRecyclerViewAdapter#onBindViewHolder
method.
@Saketme The code to transform from base adapter positions to sectioned is not complicated:
int sectionedPositionStart = positionToSectionedPosition(positionStart);
int sectionedItemCount = positionToSectionedPosition(positionStart + itemCount) - sectionedPositionStart;
notifyItemRange****(sectionedPositionStart, sectionedItemCount);
But the trouble comes when you try to animate the section changes. The difficulty with sections is that they are not usual items. They are dynamic and depend on the data in base adapter. Their appearance and disappearance depends on it. After data item is inserted/removed all section positions after must be recalculated in linear manner. This makes pretty hard to maintain section animation in the general case.
The only working approach I've found is: before any changes to the base adapter, i remove all sections with notify (for animations to take place) and after the change I rebuild the sections again and add them with notify.
Anyone had some success with section animations?