为什么 ViewHolder 上的 OnClickListener 不起作用? [英] Why does OnClickListener on a ViewHolder don't work?

查看:25
本文介绍了为什么 ViewHolder 上的 OnClickListener 不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一种方法来处理 RecyclerView 上的项目选择.我个人不喜欢通过手势的某些答案中建议的方式,我认为实现 OnClickListener,如建议的 这里here,更干净了.

I'm trying to implement a way to handle item selection on a RecyclerView. I personally don't like the way suggested in some answers on SO of passing through gestures, and I thought that implementing an OnClickListener, as suggested here and here, was waaay cleaner.

事实是……这种模式实际上不起作用!我真的无法理解为什么我的 OnClickListener.onClick从不调用.这有点像另一种方法在 onClick 可以处理之前拦截点击.

The fact is that... this pattern doesn't actually work! I'm really not able to understand why my OnClickListener.onClick is never called. It's kinda like another method intercepts the click before onClick can take care of it.

这是我的代码:

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView tvName;
        ImageView star;

        public ViewHolder(View itemView) {
            super(itemView);

            tvName = (TextView) itemView.findViewById(R.id.CHAT_ITEM_name);
            star = (ImageView) itemView.findViewById(R.id.CHAT_ITEM_star);

            Fonts.setTypeface(tvName, regular);
        }

        @Override
        public void onClick(View view) {
            int position = getLayoutPosition();
            select(position);
        }
    }

不幸的是,能够访问整个数据集中单击项目的位置对我来说非常重要,以便将其删除,因此执行诸如 indexOfChild 之类的操作也是不可接受的:我试过了,但此方法为您提供列表中 visibile 部分中项目的位置,从而使 list.remove(position) 不可能.

Unfortunately it's very important for me to able to access the position of the clicked item in the whole dataset, in order to remove it, so doing something like indexOfChild isn't acceptable too: I tried, but this method gives you the position of the item in the visibile part of the list, thus making list.remove(position) impossible.

推荐答案

查看更新后的代码:您没有将 onClickListener 设置为 ViewHolder 中的任何视图.忘记点击监听器是可以理解的错误.

Looking at the updated code: you are not setting the onClickListener to any of the views in the ViewHolder. It is an understandable mistake to forget the click listener.

只需使用:

tvName.setOnClickListener(this);
star.setOnClickListener(this);

您可以设置为两者或其中之一.也可以简单的获取这两个view的父布局,这样adapter中的整个item就可以点击了.

You can set to both or just one of them. You can also simply get the parent layout of these two views, so that the whole item itself in the adapter can be clickable.

itemView.setOnClickListener(this);

这篇关于为什么 ViewHolder 上的 OnClickListener 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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