Best way to notify RecyclerView Adapter from Viewholder?

痴心易碎 提交于 2019-12-06 04:20:02

问题


I have a RecyclerView with multiple item view types so they are broken into separate ViewHolder classes. Before, when all the ViewHolders were in the same class as the RecyclerView Adapter, I could update the adapter directly when an item was clicked or deleted. However, I separated the ViewHolders into different classes to better organize the code. Now, I cannot directly update my RecyclerView Adapter. Which of the following solutions is the best way to communicate from my ViewHolder to my Adapter? If there is a better solution than the ones I have listed, please suggest!

  1. Using a Interface with a Callback listener. Keep in mind that there might be 5 - 10 different view types so would this method require 5 - 10 interfaces?
    1. Use an Eventbus library such as Greenrobot's Eventbus.

Is an interface or eventbus solution really the best way? There surely has to be a better method for communication between views and adapters!


回答1:


I usually save reference to the adapter in activity or fragment. ViewHolders can be placed as inner classes in Adapter or as classes in separate package. You can use one interface to interact with view 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();
    }
});


来源:https://stackoverflow.com/questions/43433706/best-way-to-notify-recyclerview-adapter-from-viewholder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!