• Stars
    star
    2,073
  • Rank 22,293 (Top 0.5 %)
  • Language
    Java
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Custom Android RecyclerViewAdapters that collapse and expand

logo

Expandable RecyclerView CircleCI

Custom RecyclerViewAdapters for expanding and collapsing groups with support for multiple view types

Download

ExpandableRecyclerView:

compile 'com.thoughtbot:expandablerecyclerview:1.4'

ExpandableCheckRecyclerView:

compile 'com.thoughtbot:expandablecheckrecyclerview:1.4'

Usage

Let's say you are a rock star 🎸 and you want to build an app to show a list of your favorite Genres with a list of their top Artists.

First, define your custom ExpandableGroup class:

public class Genre extends ExpandableGroup<Artist> {

  public Genre(String title, List<Artist> items) {
    super(title, items);
  }
}

Next up, let's create the ChildViewHolder and GroupViewHolder. These are both wrappers around regular ol' RecyclerView.ViewHolders so implement any view inflation and binding methods you may need.

public class GenreViewHolder extends GroupViewHolder {

  private TextView genreTitle;

  public GenreViewHolder(View itemView) {
    super(itemView);
    genreTitle = itemView.findViewById(R.id.genre_title);
  }

  public void setGenreTitle(ExpandableGroup group) {
    genreTitle.setText(group.getTitle());
  }
}
public class ArtistViewHolder extends ChildViewHolder {

  private TextView artistName;

  public ArtistViewHolder(View itemView) {
    super(itemView);
    artistName = itemView.findViewById(R.id.artist_name);
  }

  public void setArtistName(Artist artist) {
    artistName.setText(artist.getTitle());
  }
}

Now we are ready for the juicy part - let's make our ExpandableRecyclerViewAdapter

By including your GroupViewHolder and ChildViewHolder in the definition of the class, you'll see that the onCreateGroupViewHolder and onCreateChildViewHolder methods return the correct type πŸ‘

public class GenreAdapter extends ExpandableRecyclerViewAdapter<GenreViewHolder, ArtistViewHolder> {

  public GenreAdapter(List<? extends ExpandableGroup> groups) {
    super(groups);
  }

  @Override
  public GenreViewHolder onCreateGroupViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.list_item_genre, parent, false);
    return new GenreViewHolder(view);
  }

  @Override
  public ArtistViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.list_item_artist, parent, false);
    return new ArtistViewHolder(view);
  }

  @Override
  public void onBindChildViewHolder(ArtistViewHolder holder, int flatPosition, ExpandableGroup group, int childIndex) {
    final Artist artist = ((Genre) group).getItems().get(childIndex);
    holder.setArtistName(artist.getName());
  }

  @Override
  public void onBindGroupViewHolder(GenreViewHolder holder, int flatPosition, ExpandableGroup group) {
    holder.setGenreTitle(group);
  }
}

Lastly you'll need either an Activity or Fragment to host your adapter. Once you've got that up and running, all that's left is to instantiate your fancy new GenreAdapter with a List<Genre>

public class GenreActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {

    ...

    List<Genre> genres = getGenres(); //see sample project's GenreDataFactory.java class for getGenres() method
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);

    //instantiate your adapter with the list of genres
    GenreAdapter adapter = new GenreAdapter(genres);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);

    ...

  }
}

Saving And Restoring Expand / Collapse State

If you want to save the expand and collapse state of your adapter, you have to explicitly call through to the adapters onSaveInstanceState() and onRestoreInstanceState()in the calling Activity

public class GenreActivity extends Activity {

  ...

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    adapter.onSaveInstanceState(outState);
  }

  @Override
  protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    adapter.onRestoreInstanceState(savedInstanceState);
  }
}

Programmatic Expanding and Collapsing

The ExpandableRecyclerViewAdapter exposes methods to control the expanded and collapsed state.

First up we have the toggles, .toggleGroup(int) and .toggleGroup(ExpandableGroup). These are handy for when you control the states explicitly.

public class GenreActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {

    ...

    Button showAllToggle = findViewById(R.id.show_all);
    showAllToggle.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        for (int i = adapter.groups().size() - 1; i >= 0; i--) {
          adapter.toggleGroup(i);
        }
      }
    });

  }
}

We also expose explicit methods to control the expanding and collapsing of specific groups, .expandGroup() and .collapseGroup(). For example, to expand the first group immediately:

public class GenreActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {

    ...

    adapter.expandGroup(0);

  }
}

Adding Custom Expand / Collapse Animations

If you want to add a custom Drawable that animates based on a groups state, override the expand() and collapse() methods in your GroupViewHolder:

public class GenreViewHolder extends GroupViewHolder {

  ...

  @Override
  public void expand() {
    animateExpand();
  }

  @Override
  public void collapse() {
    animateCollapse();
  }
}

Listening to Expand/Collapse events

If you want register an ExpandCollapseListener outside of the adapter, you can simply call setOnGroupExpandCollapseListener on the ExpandableRecyclerViewAdapter

  adapter.setOnGroupExpandCollapseListener(new GroupExpandCollapseListener() {
    @Override
    public void onGroupExpanded(ExpandableGroup group) {

    }

    @Override
    public void onGroupCollapsed(ExpandableGroup group) {

    }
  });

Multiple Child and Group Types

The MultiTypeExpandableRecyclerViewAdapter allows subclasses to implement multiple different view types for both children and groups.

Continuing with our genre example, let's say you wanted to display regular artists differently from your favorite artists. Let's start by making a new FavoriteArtistViewHolder

public class FavoriteArtistViewHolder extends ChildViewHolder {

  private TextView favoriteArtistName;

  public FavoriteArtistViewHolder(View itemView) {
    super(itemView);
    favoriteArtistName = (TextView) itemView.findViewById(R.id.list_item_favorite_artist_name);
  }

  public void setArtistName(String name) {
    favoriteArtistName.setText(name);
  }

Just like the regular ArtistViewHolder, FavoriteArtistViewHolder must extends ChildViewHolder.

Next up, let's create a subclass of MultiTypeExpandableRecyclerViewAdapter called MultiTypeGenreAdapter and let's add two static ints representing our two artist view types:

public class MultiTypeGenreAdapter extends MultiTypeExpandableRecyclerViewAdapter<GenreViewHolder, ChildViewHolder> {


  public static final int FAVORITE_VIEW_TYPE = 3;
  public static final int ARTIST_VIEW_TYPE = 4;
  ...

Notice we started used values > 2. That's because ExpandableListPosition.CHILD and ExpandableListPositon.GROUP are 1 and 2 respectively so they are already taken.

Since we only want a single view type for groups, we only need to override getChildViewType(). As getGroupViewType() will default to ExpandableListPosition.GROUP.

  @Override
  public int getChildViewType(int position, ExpandableGroup group, int childIndex) {
    if (((Genre) group).getItems().get(childIndex).isFavorite()) {
      return FAVORITE_VIEW_TYPE;
    } else {
      return ARTIST_VIEW_TYPE;
    }
  }

Since we provided custom view types for our children, we must also override isChild()

  @Override
  public boolean isChild(int viewType) {
    return viewType == FAVORITE_VIEW_TYPE || viewType == ARTIST_VIEW_TYPE;
  }

And now, just like in any other RecyclerView.Adapter in our onCreateChildViewHolder and our onBindChildViewHolder we can use the provided parameters to switch on the different view tyeps:

  @Override
  public ChildViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
    switch (viewType) {
      case ARTIST_VIEW_TYPE:
        View artist = from(parent.getContext()).inflate(R.layout.list_item_artist, parent, false);
        return new ArtistViewHolder(artist);
      case FAVORITE_VIEW_TYPE:
        View favorite =
            from(parent.getContext()).inflate(R.layout.list_item_favorite_artist, parent, false);
        return new FavoriteArtistViewHolder(favorite);
      default:
        throw new IllegalArgumentException("Invalid viewType");
    }
  }

  @Override
  public void onBindChildViewHolder(ChildViewHolder holder, int flatPosition, ExpandableGroup group,
      int childIndex) {
    int viewType = getItemViewType(flatPosition);
    Artist artist = ((Genre) group).getItems().get(childIndex);
    switch (viewType) {
      case ARTIST_VIEW_TYPE:
        ((ArtistViewHolder) holder).setArtistName(artist.getName());
        break;
      case FAVORITE_VIEW_TYPE:
        ((FavoriteArtistViewHolder) holder).setArtistName(artist.getName());
    }
  }

Expandable Check RecyclerView

An extension of expandablerecyclerview for checking single or multiple children within a group

The setup for the single and multi check versions is very similar to the expandablerecyclerview we walked through above. Here are a few of the notable differences...

CheckedExpandableGroup

Instead of ExpandableGroup you must use CheckedExpandableGroup. CheckedExpandableGroup is a subclass of ExpandableGroup that uses a SparseBooleanArray to hold onto which of it's children are checked.

The expandablecheckrecyclerview library comes with two default implementations - SingleCheckExpandableGroup and MultiCheckExpandableGroup.

Clearing Choices

The CheckableChildRecyclerViewAdapter has a clearChoices() which un checks any currently checked children.

CheckableChildViewHolder

The CheckableChildViewHolder is a subclass of ChildViewHolder that has a Checkable widget. The Checkable interface is initially not set, so in order to see your children view states update, you must set a View that implements Checkable in your view holder.

public class SingleCheckArtistViewHolder extends CheckableChildViewHolder {

  private CheckedTextView artistName;

  public SingleCheckArtistViewHolder(View itemView) {
    super(itemView);
    artistName = (CheckedTextView) itemView.findViewById(R.id.list_item_singlecheck_artist_name);
  }

  @Override
  public Checkable getCheckable() {
    return artistName;
  }
  ...
}

Listening to Child Click Events

There is a custom callback for click events on children of a CheckedExpandableGroup which returns you the View of the row item that was clicked, the current checked state of the child, the containing CheckedExpandableGroup group and the index of the child that was clicked.

  adapter.setChildClickListener(new OnCheckChildClickListener() {
    @Override
    public void onCheckChildCLick(View v, boolean checked, CheckedExpandableGroup group,
        int childIndex) {
    }
  });

Sample App

To see the complete code for all the above examples along with unit tests for the adapters check out the sample app. The app has the following packages:

expand

An example of basic ExpandableRecyclerViewAdapter

multicheck

An example of a CheckableChildRecyclerViewAdapter using MultiCheckExpandableGroup

single check

An example of a CheckableChildRecyclerViewAdapter using SingleCheckExpandableGroup

multi type

An example of a MultiTypeExpandableRecyclerViewAdapter using two different child view holders

Contributing

See the CONTRIBUTING document. Thank you, contributors!

License

Expandable RecyclerView is Copyright (c) 2016 thoughtbot, inc. It is free software, and may be redistributed under the terms specified in the LICENSE file.

About

Expandable RecyclerView is maintained by @mandybess

thoughtbot

Expandable RecyclerView is maintained and funded by thoughtbot, inc. The names and logos for thoughtbot are trademarks of thoughtbot, inc.

We love open source software! See our other projects or hire us to help build your product.

More Repositories

1

guides

A guide for programming in style.
Ruby
9,327
star
2

bourbon

A Lightweight Sass Tool Set
Ruby
9,100
star
3

paperclip

Easy file attachment management for ActiveRecord
Ruby
9,055
star
4

laptop

A shell script to set up a macOS laptop for web and mobile development.
Shell
8,416
star
5

dotfiles

A set of vim, zsh, git, and tmux configuration files.
Shell
7,942
star
6

factory_bot

A library for setting up Ruby objects as test data.
Ruby
7,826
star
7

administrate

A Rails engine that helps you put together a super-flexible admin dashboard.
JavaScript
5,867
star
8

neat

A fluid and flexible grid Sass framework
Ruby
4,444
star
9

suspenders

A Rails template with our standard defaults, ready to deploy to Heroku.
Ruby
3,922
star
10

til

Today I Learned
3,903
star
11

clearance

Rails authentication with email & password.
Ruby
3,629
star
12

shoulda-matchers

Simple one-liner tests for common Rails functionality
Ruby
3,513
star
13

Argo

Functional JSON parsing library for Swift
Swift
3,487
star
14

high_voltage

Easily include static pages in your Rails app.
Ruby
3,141
star
15

rcm

rc file (dotfile) management
Perl
2,990
star
16

factory_bot_rails

Factory Bot β™₯ Rails
Ruby
2,972
star
17

shoulda

Makes tests easy on the fingers and the eyes
Ruby
2,196
star
18

capybara-webkit

A Capybara driver for headless WebKit to test JavaScript web apps
Ruby
1,969
star
19

gitsh

An interactive shell for git
Ruby
1,957
star
20

Tropos

Weather and Forecasts for Humans
Swift
1,518
star
21

refills

[no longer maintained]
CSS
1,513
star
22

design-sprint

Product Design Sprint Material
1,415
star
23

bitters

Add a dash of pre-defined style to your Bourbon.
HTML
1,398
star
24

griddler

Simplify receiving email in Rails (deprecated)
Ruby
1,376
star
25

trail-map

Trails to help designers and developers learn various topics.
1,219
star
26

appraisal

A Ruby library for testing your library against different versions of dependencies.
Ruby
1,194
star
27

hotwire-example-template

A collection of branches that transmit HTML over the wire.
Ruby
1,033
star
28

parity

Shell commands for development, staging, and production parity for Heroku apps
Ruby
890
star
29

Runes

Infix operators for monadic functions in Swift
Swift
830
star
30

cocaine

A small library for doing (command) lines.
Ruby
788
star
31

fishery

A library for setting up JavaScript objects as test data
TypeScript
759
star
32

flutie

View helpers for Rails applications
Ruby
730
star
33

TBAnnotationClustering

Example App: How To Efficiently Display Large Amounts of Data on iOS Maps
Objective-C
728
star
34

vim-rspec

Run Rspec specs from Vim
Vim Script
650
star
35

climate_control

Modify your ENV
Ruby
512
star
36

constable

Better company announcements
Elixir
511
star
37

carnival

An unobtrusive, developer-friendly way to add comments
Haskell
501
star
38

ruby-science

The reference for writing fantastic Rails applications
Ruby
494
star
39

Curry

Swift implementations for function currying
Swift
494
star
40

pacecar

Generated scopes for ActiveRecord classes
Ruby
437
star
41

hoptoad_notifier

Reports exceptions to Hoptoad
Ruby
408
star
42

fake_stripe

A Stripe fake so that you can avoid hitting Stripe servers in tests.
Ruby
393
star
43

json_matchers

Validate your JSON APIs
Ruby
384
star
44

Swish

Nothing but Net(working)
Swift
363
star
45

superglue

A productive library for Classic Rails, React and Redux
JavaScript
361
star
46

paul_revere

A library for "one off" announcements in Rails apps.
Ruby
298
star
47

stencil

Android library, written exclusively in kotlin, for animating the path created from text
Kotlin
282
star
48

Perform

Easy dependency injection for storyboard segues
Swift
280
star
49

upcase

Sharpen your programming skills.
Ruby
275
star
50

testing-rails

Source code for the Testing Rails book
HTML
269
star
51

proteus

[no longer maintained]
Ruby
254
star
52

Delta

Managing state is hard. Delta aims to make it simple.
Swift
246
star
53

foundry

Providing a new generation of vector assets and infinite possibility for the interactive web and mobile applications
CSS
233
star
54

limerick_rake

A collection of useful rake tasks.
Ruby
232
star
55

shoulda-context

Shoulda Context makes it easy to write understandable and maintainable tests under Minitest and Test::Unit within Rails projects or plain Ruby projects.
Ruby
231
star
56

backbone-support

lumbar support
JavaScript
227
star
57

terrapin

Run shell commands safely, even with user-supplied values
Ruby
216
star
58

Superb

Pluggable HTTP authentication for Swift.
Swift
203
star
59

jack_up

[DEPRECATED] Easy AJAX file uploading in Rails
Ruby
202
star
60

fistface

DIY @font-face web service.
Ruby
182
star
61

squirrel

Natural-looking Finder Queries for ActiveRecord
Ruby
178
star
62

sortable_table

Sort HTML tables in your Rails app.
Ruby
157
star
63

write-yourself-a-roguelike

Write Yourself A Roguelike: Ruby Edition
Ruby
155
star
64

pester

Automatically ask for a PR review
Ruby
147
star
65

jester

REST in Javascript
JavaScript
146
star
66

complexity

A command line tool to identify complex code
Rust
142
star
67

kumade

Heroku deploy tasks with test coverage (DEPRECATED, NO LONGER BEING DEVELOPED)
Ruby
137
star
68

proteus-middleman

[no longer maintained]
CSS
133
star
69

FunctionalJSON-swift

Swift
133
star
70

capybara_discoball

Spin up an external server just for Capybara
Ruby
128
star
71

tropos-android

Weather and Forecasts for Humans
Kotlin
128
star
72

ModalPresentationView

Remove the boilerplate of modal presentations in SwiftUI
Swift
125
star
73

react-native-typescript-styles-example

A template react native project for ergonomic styling structure and patterns.
TypeScript
123
star
74

vimulator

A JavaScript Vim simulator for demonstrations
JavaScript
119
star
75

bourne

[DEPRECATED] Adds test spies to mocha.
Ruby
114
star
76

formulator

A form library for Phoenix
Elixir
106
star
77

poppins

Gifs!
Objective-C
106
star
78

tailwindcss-aria-attributes

TailwindCSS variants for aria-* attributes
JavaScript
100
star
79

ghost-theme-template

A project scaffold for building ghost themes using gulp, node-sass, & autoprefixer
HTML
91
star
80

paperclip_demo

Paperclip demo application
Ruby
87
star
81

middleman-template

The base Middleman application used at thoughtbot, ready to deploy to Netlify.
CSS
86
star
82

proteus-jekyll

[no longer maintained]
CSS
84
star
83

report_card

metrics and CI are for A students.
Ruby
77
star
84

ios-sample-blender

Sample code for the Blending Modes blog post
Objective-C
76
star
85

yuri-ita

Create powerful interfaces for filtering, searching, and sorting collections of items.
Ruby
76
star
86

baccano

[no longer maintained]
HTML
74
star
87

goal-oriented-git

A practical book about using Git
HTML
73
star
88

ios-on-rails

A guide to building a Rails API and iOS app
HTML
72
star
89

art_vandelay

Art Vandelay is an importer/exporter for Rails 6.0 and higher.
Ruby
71
star
90

maybe_haskell

Programming without Null
HTML
71
star
91

redbird

A Redis adapter for Plug.Session
Elixir
70
star
92

maintaining-open-source-projects

A successful open source project is not only one that is original, solves a particular problem well, or has pristine code quality. Those are but the tip of the iceberg, which we'll thoroughly dissect with this book.
Shell
67
star
93

templates

Documentation templates for open source projects.
64
star
94

FOMObot

A slack bot to help with FOMO.
Haskell
61
star
95

BotKit

BotKit is a Cocoa Touch static library for use in iOS projects. It includes a number of helpful classes and categories that are useful during the development of an iOS application.
Objective-C
61
star
96

react-native-template

Template React Native project to be used with Cookiecutter
JavaScript
60
star
97

CombineViewModel

An implementation of the Model-View-ViewModel (MVVM) pattern using Combine.
Swift
59
star
98

flightdeck

Terraform modules for rapidly building production-grade Kubernetes clusters following SRE practices
HCL
55
star
99

design-for-developers-starter-kit

A starter project for design for developer students
CSS
54
star
100

mile_marker

Mark off HTML implementation expectations with clear signage
Ruby
53
star