Stan Malcolm Stan Malcolm - 18 days ago 7
Android Question

RecyclerView with expandable items

I need to make an expandable

RecyclerView
, with only one opened item per click (all others must close).
I know there is possibility to do this with the help of
ExpandableListView
and then use next code:

elv.setOnGroupExpandListener(new OnGroupExpandListener() {

@Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
elv.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});


but is there the way to make the same with using
RecyclerView
?

Answer

Here is a nice tutorial for expending RecyclerView from Big Nerd Ranch

Summary:

  • Define two layouts: One for parent items and one for child items.
  • Define two ViewHolders for these layouts.
  • Define two classes for parent and child objects.
  • Parent object has to implement ParentObject interface.
  • Define custom adapter.
  • Call setParentAndIconExpandOnClick(true) on adapter.

For only one expanded view at a time, you can keep track of the last expanded view and close it when user cliced new one.