Code Recipe: A Generic RecyclerView.Adapter Implementation
How many times have you created an Adapter
for a RecyclerView
? Maybe infinite! Every other list requires a new Adapter
implementation which ends up with a lot of boilerplate code. But have you ever thought of making an implementation that can work for all of your lists?
Well, today we gonna make one and close it once for all. And I am not just gonna give you the code but also explain how it works, how you can write your own similar implementations and caveats:-
How does it work?
If you try you will find that it’s only the logic and basically under Adapter.onBindViewHolder
call which changes for every other Adapter
. The rest of it can be injected as a dependency at the time of instantiation. Same is done in the SimpleRecyclerViewAdapter
, data and layout resource can be added at instantiation and the logic can be passed using:
SimpleRecyclerViewAdapter.setOnBindViewHolderListener
(OnBindViewHolderListener onBindViewHolderListener)
Caveat
This source code abides developer to call View.findViewById
every time SimpleRecyclerViewAdapter.onBindViewHolder
is called which is not appropriate in many ways. The best practice is always to store the reference of the View
so that no unnecessary calls are made to View.findViewById()
though nothing is a rule of thumb in programming and sometimes it's more of a convenience the developer has to think about.
Code
Example
final SimpleRecyclerViewAdapter<Object> adapter = new SimpleRecyclerViewAdapter<>(R.layout.layout_activity_protein);
adapter.setItems(items);
adapter.setOnBindViewHolderListener(((viewHolder, pos) -> {
.
.
.
}));
RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(activity, RecyclerView.VERTICAL, false));
recyclerView.setAdapter(adapter);
How to write similar implementations?
To make things clearer I have a separated it out in different story:-