Best way to notify RecyclerView adapter from Viewholder?
I have a RecyclerView with several types of item views, so they are split into separate ViewHolder classes. Previously, when all ViewHolders were in the same class as the RecyclerView Adapter, I could update the adapter directly when the item was clicked or removed. However, I've split the ViewHolders into different classes to better organize the code. Now I cannot directly update the RecyclerView adapter. Which of the following solutions is the best way to communicate with my ViewHolder in my adapter? If there is a better solution than the ones I have listed, please suggest!
- Using an interface with a callback listener. Keep in mind that there might be 5-10 different view types, so this method would require 5-10 interfaces?
- Use an Eventbus library like Greenrobot Eventbus.
Is the interface solution or eventbus really the best? There must of course be a better way to communicate between views and adapters!
source to share
I usually keep the adapter reference in an activity or fragment. ViewHolders can be hosted as inner classes in an adapter or as classes in a separate package. You can use one interface to interact with holders. You just need to implement it in your activity or fragment. For example:
public class MyAdapter extends RecyclerView.Adapter<VH> {
private MyInterface mInterface;
public MyAdapter(MyInterface i) {
mInterface = i;
}
//... some code to create view holders
//binding
@Override
protected void onBindItemViewHolder(ViewHolder viewHolder, final int position, int type) {
viewHolder.bindView(position, mInterface); //call methods of interface in bindView() methods of your viewHolders
}
interface MyInterface {
void someEvent();
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView mText;
ViewHolder(View root) {
super(root);
mText = (TextView)root.findViewById(R.id.text)
}
void bindView(int pos, MyAdapter.MyInterface myInterface) {
mText.setOnClickListener(v -> myInterface.someEvent());
//...some other code
}
}
And somewhere in your activity or fragment:
final MyAdapter adapter = new MyAdapter(new MyAdapter.MyInterface() {
@Override
public void someEvent() {
adapter.notifyDataSetChanged();
}
});
source to share