Best approach to communicate between Fragment/Activity and RecyclerView.Adapter?

…衆ロ難τιáo~ 提交于 2019-12-13 08:30:06

问题


My fragment:

public  class FragmentSort extends Fragment {
  @BindView(R.id.sortRecyclerView)
  RecyclerView sortRecyclerView;
  protected RecyclerView.Adapter adapter;

  @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View rootView = inflater.inflate(layoutResId, container, false);
       adapter = new StoreListItemAdapter(getActivity(), collection);
       sortRecyclerView.setAdapter((RecyclerView.Adapter) adapter);
       return rootView;
}

     @Subscribe
public void onStoreClickEvent(Store store) {
    Debug.d(TAG, "onStoreClickEvent: store = " + store);
    handleFilterItemSelect(store.getAddress());
 }
}

Here my custom adapter:

public class StoreListItemAdapter extends RecyclerView.Adapter {
    private Context context;
    private List<?> data = new ArrayList<>();

  public DataBindingRecyclerViewAdapter(Context context, List<?> data) {
        this.context = context;
        this.data = data;
  }

  public void onClick(Store store) {
    EventBus.getDefault().post(store);
  }
}

When click on some item in list then call method onClick(). So I need my fragment to handle click of item. To to do this I use EventBus. After click I call

EventBus.getDefault().post(store);

And as result in fragment call method:

onStoreClickEvent(Store store)

So this is my model to communicate between my custom fragment and my custom adapter.

It's work. Fine.

The quesion is: Is this a best approach for communicate between fragment and adapter?

P.S. My custom adapter can use by fragment, activity or custom view.


回答1:


An alternative would be to create a listener interface like this:

public interface OnStoreItemClickListener {

    public void onStoreItemClicked(Store item);    

}

Then, in your Adapter, you declare a field of type OnStoreItemClickListener and you create a setter method for it.

When you detect a click, you simply check if your listener is set and call the onStoreItemClicked() method.

You can register a listener via the setter from wherever you need.



来源:https://stackoverflow.com/questions/48462272/best-approach-to-communicate-between-fragment-activity-and-recyclerview-adapter

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