Where should I place setOnClickListener in a RecyclerView Adapter

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 03:45:46

Both options have their pros and cons.

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.

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.

Your number 1 solution is the best as you proposed since that assignment will not be called in the Binding at each invalidate triggered by notify..() methods. I know also others solutions but you need to implement android.view.GestureDetector in your activity.

If you want others improvements on the adapter, take a look at mine FlexibleAdapter https://github.com/davideas/FlexibleAdapter and feel free to implement in your project.

IMHO: I like number 1.

Since your calling into new ViewHolder(View) your really setting your onClickListener before actually displaying your content. This is nice because by the time onBindView is called, your onClickListener has already been set on your view.

I think its also cleaner code to do this in your constructor ViewHolder(View)

In ViewHolder() i guess, since you define what view is holded and what it has inside and other functions.

But onBindViewHolder() you say that view, which is defined in ViewHolder, will have this text, this image...

You should always check if getAdapterPosition is >= 0 because it could be -1 (NO_POSITION) in rare cases that can lead to a crash in your app. https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder#getadapterposition

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