我应该在哪里将setOnClickListener放在RecyclerView适配器中 [英] Where should I place setOnClickListener in a RecyclerView Adapter

查看:132
本文介绍了我应该在哪里将setOnClickListener放在RecyclerView适配器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Internet上的教程中,他们通过RecyclerView的Adapter中的setOnClickListener定义了两种方式:在ViewHolder内部或BindViewHolder内部.

In tutorials on internet where they setOnClickListener in Adapter of RecyclerView they define it in two ways : either inside ViewHolder or inside BindViewHolder.

我的问题是哪种方法更好,请推荐其他任何可行的方法

My Question is which one is a better approach, Please recommend any another approach if available

1)在ViewHolder中:

1) inside ViewHolder:

public static class ViewHolder extends RecyclerView.ViewHolder {

    public ViewHolder(View itemView) {
        super(itemView);
        tvSrc = (TextView) itemView.findViewById(R.id.tvSrc);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), "inside viewholder position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
            }
        });
    }

2)在BindViewHolder中

2) inside BindViewHolder

public void onBindViewHolder(DisplayTrainsAdapter.ViewHolder viewHolder, final int position) {

    viewHolder.tvSrc.setText(mDataset.get(position).strSrc);
    viewHolder.tvSrc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(v.getContext(), "position = " + getItemId(position), Toast.LENGTH_SHORT).show();
        }
    });
}    

推荐答案

两种选择都有其优缺点.

Both options have their pros and cons.

例如,如果单击了一个按钮,而您想更改按钮的文本,那么您可能应该使用在ViewHolder中设置onClick侦听器的选项.除此之外,它还使您的代码看起来更简洁.

For example, if a Button is clicked and you want to change the text of your button, then you should probably use the option where you setup the onClick listener in the ViewHolder. Apart from this reason, it also makes your code look cleaner.

但是,如果说,单击按钮时,您想要在与单击的按钮相同的索引/位置中更改TextView的文本,则需要使用在其中设置onClick侦听器的选项onBindViewHolder方法.

However, if say, when the Button is clicked, you want to change the text of a TextView in the same index/position as the button that was clicked, you will need to use the option where you setup the onClick listener in the onBindViewHolder method.

这篇关于我应该在哪里将setOnClickListener放在RecyclerView适配器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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