在Fragment/Activity和RecyclerView.Adapter之间进行通信的最佳方法? [英] Best approach to communicate between Fragment/Activity and RecyclerView.Adapter?

查看:120
本文介绍了在Fragment/Activity和RecyclerView.Adapter之间进行通信的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的片段:

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);
  }
}

当单击列表中的某个项目时,请调用方法 onClick ().所以我需要我的片段来处理项目的点击.为此,我使用EventBus.点击后,我打电话

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);

结果是片段调用方法:

onStoreClickEvent(Store store)

这是我的模型,用于在我的自定义片段和我的自定义适配器之间进行通信.

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

这是工作.好吧.

问题是:这是在片段和适配器之间进行通信的最佳方法吗?

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

P.S.我的自定义适配器可以按片段,活动或自定义视图使用.

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

推荐答案

一种替代方法是创建一个如下所示的侦听器接口:

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

public interface OnStoreItemClickListener {

    public void onStoreItemClicked(Store item);    

}

然后,在适配器中,声明一个类型为 OnStoreItemClickListener 的字段,并为其创建一个setter方法.

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

检测到点击时,只需检查是否设置了侦听器,然后调用 onStoreItemClicked()方法.

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.

这篇关于在Fragment/Activity和RecyclerView.Adapter之间进行通信的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆