在recyclerview中附加onClickListener的最佳位置 [英] Best place to attach onClickListener in recyclerview

查看:85
本文介绍了在recyclerview中附加onClickListener的最佳位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我在看一些有关回收站视图的教程,但其中一些使用viewHolder构造函数来附加onClick侦听器,而另一些则使用onBindViewHolder方法.哪种方法是附加onclicklistener的最佳位置.我真的很困惑

While i was looking at some tutorials about recycler view.some of them used the viewHolder constructor to attach the onClick listener while some of them used the onBindViewHolder method. which method is the best place to attach the onclicklistener. i'm really confused

推荐答案

每次将视图与数据绑定时,都会调用方法onBindViewHolder.因此,这里不是设置点击侦听器的最佳位置.您不必为一个View多次设置OnClickListener.因此,最好的解决方案是在onCreateViewHolder方法中设置点击监听器.但是重要的是如何在点击侦听器上实现.例如,如果要从列表中获取某些模型,则可以使用ViewHolder中的getAdapterPosition()方法.

The method onBindViewHolder is called every time when you bind your view with data. So there is not the best place to set click listener. You don't have to set OnClickListener many times for the one View. So the best solution is to set click listener in onCreateViewHolder method. But the important thing is a how do you implement on click listener. If you for example want to get some model from list you can use getAdapterPosition() method from ViewHolder.

看看例子

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

    final View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.view_magazine_list_item, null);

    final ViewHolder result = new ViewHolder(view);
    view.setOnClickListener(new OnClickListener(){
          @Override
          public void onClick(View v){
             YourObject yourobject = yourObjectsList.get(result.getAdapterPosition()));
          }
    });
    return result;
}

这篇关于在recyclerview中附加onClickListener的最佳位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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