如何使用RxJava处理回收站视图的项目单击 [英] How to handle Item clicks for a recycler view using RxJava
问题描述
我很想找出对回收者视图中的项目单击做出响应的最佳方法是什么.
I was interested to find out what is the best way to respond to a item click of a recycler view.
通常,我将向ViewHolder添加一个onclick()侦听器,并将结果通过接口传递回活动/片段.
Normally I would add a onclick() listener to the ViewHolder and pass back results to the activity/fragment through a interface.
我考虑过要在onBindViewHolder中添加一个Observable,但是我不想为每个项目绑定创建一个新的Observable.
I thought about adding a Observable in the onBindViewHolder but i do not want to create a new Observable for every item binding.
推荐答案
您可以使用 RxBinding ,然后在适配器内部创建一个主题,然后将所有事件重定向到该主题,并仅创建该主题的吸气剂以充当可观察对象,最后只订阅该可观察对象.
You can use RxBinding and then create a subject inside of your adapter, then redirect all the events to that subject and just create a getter of the subject to act as an observable and finally just subscribe you on that observable.
private PublishSubject<View> mViewClickSubject = PublishSubject.create();
public Observable<View> getViewClickedObservable() {
return mViewClickSubject.asObservable();
}
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup pParent, int pViewType) {
Context context = pParent.getContext();
View view = (View) LayoutInflater.from(context).inflate(R.layout.your_item_layout, pParent, false);
ViewHolder viewHolder = new ViewHolder(view);
RxView.clicks(view)
.takeUntil(RxView.detaches(pParent))
.map(aVoid -> view)
.subscribe(mViewClickSubject);
return viewHolder;
}
一个用法示例可以是:
mMyAdapter.getViewClickedObservable()
.subscribe(view -> /* do the action. */);
这篇关于如何使用RxJava处理回收站视图的项目单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!