AndroidPub
Published in

AndroidPub

Android DTT #19 — Adapter Delegates

Handling a regular RecyclerView.Adapter with multiple view types can be difficult. The class will be full of code which difficult to manage when we want to add more type to the adapter. It even may become spaghetti code.

Spaghetti, yummy. Spaghetti code, yuck-sy.

Here’s one example of adapter that handles 2 types:

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {    int TYPE_CAR = 0;
int TYPE_TRAIN = 1;
int getItemViewType(int position) {
if (items.get(position) instanceof CAR) return TYPE_CAR;
else return TYPE_TRAIN;
}
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
if (viewType == TYPE_CAR) return createCarViewHolder(parent);
else return createTrainViewHolder(parent);
}
public void onBindViewHolder(ViewHolder holder, int position) {
if (holder instanceof CarViewHolder) bindCar();
else bindTrain();
}
// CarViewHolder, TrainViewHolder
}

This clearly violates the SRP (Single Responsibility Principle) that states one class should be kept focused on single concern. In the code above, the adapter deals with too many responsibilities: creating ViewHolder, determining which ViewHolder to use, binding items to ViewHolder etc.

Hannes Dorfmann (sockeqwe) creates a library to encapsulate some of the responsibility to a class called AdapterDelegate. This delegate will have the responsibility to determine whether it can handle the given item, create ViewHolder and bind content to it.

Here’s what an AdapterDelegate would like:

public class CarAdapterDelegate implements AdapterDelegate<List<Vehicle>> {
public boolean isForViewType(List<Vehicle> items, int position) {
return items.get(position) instanceof Car;
}
public ViewHolder onCreateViewHolder(ViewGroup parent) {
// create CarViewHolder
}
public void onBindViewHolder(ViewHolder holder, int position) {
// bind CarViewHolder
}
public static class CarViewHolder {
// view fields, findViewById etc
}
}

The CarAdapterDelegate responsible of creating the CarViewHolder, binding content to CarViewHolder without the class knowing of others Vehicle or ViewHolder.

Not to mention that you can also use CarAdapterDelegate to different adapter. Since the code is not living on the adapter anymore.

You can read the full motivation of this pattern in Hanness’s blog.

If you like this, hit that heart button and recommend it to your friends.

ADTT (Android Development Tips and Tricks) is a 31 series of blog posts that I’m trying to finish in throughout May. Click here for index.

--

--

The (retired) Pub(lication) for Android & Tech, focused on Development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store