https://github.com/fernandospr/android-groups-recyclerview-adapter
https://github.com/fernandospr/android-groups-recyclerview-adapter
Last synced: about 1 year ago
JSON representation
- Host: GitHub
- URL: https://github.com/fernandospr/android-groups-recyclerview-adapter
- Owner: fernandospr
- Created: 2016-11-07T19:25:04.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2018-03-28T18:18:27.000Z (about 8 years ago)
- Last Synced: 2025-03-28T20:11:15.025Z (about 1 year ago)
- Language: Java
- Size: 86.9 KB
- Stars: 3
- Watchers: 2
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
**RecyclerView.Adapter** supports heterogenous layouts, however, when you have to show multiple arrays of heterogenous object classes, it's difficult to write the code for `getItemViewType` and `onBindViewHolder`.
Usually, one has to iterate through each array, doing explicit casts and/or a bunch of ifs, modifying the `position` value to match the corresponding array.
**GroupsRecyclerViewAdapter** allows to add groups of items (it could also be a group of a single item, e.g. a header or a footer), easing the development of the use cases mentioned above.
# Usage
* Suppose you have the following MyModel class.
```
public class MyModel {
private String name;
private String lastname;
// getters/setters
}
```
* Create your view holders.
```
private class MyModelViewHolder extends RecyclerView.ViewHolder {
private final TextView name;
private final TextView lastname;
MyModelViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
lastname = (TextView) itemView.findViewById(R.id.lastname);
}
}
```
* Create your custom Group classes (inheriting from the Group class).
```
private class MyModelGroup extends Group {
}
```
* Inside your group class, specify the view type.
```
MyModelGroup(@NonNull List items) {
super(MODEL_VIEW_TYPE, items);
}
```
* Inside your group class, override `onBindViewHolder` and `onCreateViewHolder`.
```
@Override
public void onBindViewHolder(MyModelViewHolder holder, int position) {
MyModel myModel = getItems().get(position);
holder.name.setText(myModel.getName());
holder.lastname.setText(myModel.getLastname());
}
@Override
public MyModelViewHolder onCreateViewHolder(@NonNull ViewGroup parent,
@NonNull LayoutInflater inflater) {
View v = inflater.inflate(R.layout.my_model_item, parent, false);
return new MyModelViewHolder(v);
}
```
* Finally, instantiate **GroupsRecyclerViewAdapter** in your Activity/Fragment and add groups.
```
GroupsRecyclerViewAdapter adapter = new GroupsRecyclerViewAdapter();
Group group = new MyModelGroup(myModelList);
adapter.addGroup(group);
Group group2 = MyModel2Group(myModel2List);
adapter.addGroup(group2);
...
```