【译】优雅的监听RecyclerView Item的单击、长按事

2016-10-13  本文已影响2633人  artshell

原文链接:http://www.littlerobots.nl/blog/Handle-Android-RecyclerView-Clicks/

RecyclerView是一个非常强大的组件类,相对于ListView来说你应该考虑使用RecyclerView来构建列表界面展现数据。它提供了很多灵活且已内置的回调接口让你易于实现动效功能和定制布局管理器。

不幸的是RecyclerView并没有像ListView那样提供当单击item时触法一个OnItemClickListener事件的功能。RecyclerView允许你通过给Adapter传递一个OnClickListener对象,随后在adapter中传递给ViewHolder,为了捕获一个单击事件这种方式稍显复杂。

[译者本人曾经踩过一个坑:在给Adapter传递OnClickListener对象时,将该字段设置成了类变量(static修饰符)随后在ViewHolder中通过 Adapter.xxxListener 的方式调用,奇葩的bug诞生了,单击item时偶发性无响应。解决方法* — 改成实例字段再传递给ViewHolder*]

幸运的是RecyclerView提供了一个addOnItemTouchListener
来捕获item的所有触摸事件。你可以在OnItemTouchListener的逻辑代码中使用GestureDetector计算出单击、长按等事件。在你的计算代码中稍有不慎GestureDetector会拦截触摸事件并搞砸事情,在这种情况下item view实际上是接受不到触摸事件以致于用户得不到视觉和听觉上的反馈。

下边给出一段代码来说明使用GestureDetector的糟糕情况,也是译者曾经踩过的坑

/**
 * Created by artshell on 2015/5/24 0024.
 * 872780008@qq.com
 */
public class PopularCityAdapter extends RecyclerView.Adapter<PopularCityAdapter.PopularCityViewHolder> {
    public static final String TAG = "PopularCityAdapter";

    // code ...
    private OnItemClickListener mOnItemClickListener;
   
    public interface OnItemClickListener {
        /**
         * @param pView     child view of RecyclerView's layout
         * @param pPosition {@link RecyclerView#getChildAdapterPosition(View)}
         * @see {@link RecyclerView.ViewHolder#getAdapterPosition()}
         */
        void onRecyclerItemClick(View pView, int pPosition);
    }

    /**
     * @param pOnItemClickListener 单击事件监听器
     */
    public void setOnItemClickListener(OnItemClickListener pOnItemClickListener) {
        mOnItemClickListener = pOnItemClickListener;
    }

    // 其它 Adapter 实现代码省略 ...

    public static class RecyclerViewItemClickListener implements RecyclerView.OnItemTouchListener {
        private OnItemClickListener mItemClickListener;
        private GestureDetector mGestureDetector;

        public RecyclerViewItemClickListener(Context pContext, OnItemClickListener pItemClickListener) {
            mItemClickListener = pItemClickListener;
            mGestureDetector = new GestureDetector(pContext, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            View childView = rv.findChildViewUnder(e.getX(), e.getY());
            int position = rv.getChildAdapterPosition(childView);
            if (childView != null && position != RecyclerView.NO_POSITION && mItemClickListener != null && mGestureDetector.onTouchEvent(e)) {
                mItemClickListener.onRecyclerItemClick(childView, position);
            }
            return false; /* 这里应该返回false,应该让事件继续传递下去,否则只是处理了Touch事件,而click事件得不到执行 */
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        }
    }
}

我想到一个方案,就是通过RecyclerView item中的view,确切的说像ViewHolder.getItemView()获取view来处理单击事件。作者在卖关子

封装后,像这样:

    ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
        @Override
        public void onItemClicked(RecyclerView recyclerView, int position, View v) {
            // do it
        }
    });

使用过TwoWayView这个开源项目的用户可能注意到了ItemClickSupport与项目中的实现方式很像,实际上在此之前我在Bundle这个app中使用TwoWayViews时踩了些坑,里边用的技术就是上边提到的RecyclerView.OnItemTouchListener。当我实现ItemClickSupport后,去查看TwoWayView 发现两种实现方式类似,我觉得TwoWayView中api的实现方式很优雅而没有多次传递 xxxListener。

相对于TwoWayView 中的实现方式我使用的是OnChildAttachStateChangeListener传递一个OnClickListener对象给ViewHolder中的itemView而不是定制OnTouchListener来达到目的。

代码如下:

public class ItemClickSupport {
    private final RecyclerView mRecyclerView;
    private OnItemClickListener mOnItemClickListener;
    private OnItemLongClickListener mOnItemLongClickListener;
    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mOnItemClickListener != null) {
                RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v);
                mOnItemClickListener.onItemClicked(mRecyclerView, holder.getAdapterPosition(), v);
            }
        }
    };
    private View.OnLongClickListener mOnLongClickListener = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            if (mOnItemLongClickListener != null) {
                RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v);
                return mOnItemLongClickListener.onItemLongClicked(mRecyclerView, holder.getAdapterPosition(), v);
            }
            return false;
        }
    };
    private RecyclerView.OnChildAttachStateChangeListener mAttachListener
            = new RecyclerView.OnChildAttachStateChangeListener() {
        @Override
        public void onChildViewAttachedToWindow(View view) {
            if (mOnItemClickListener != null) {
                view.setOnClickListener(mOnClickListener);
            }
            if (mOnItemLongClickListener != null) {
                view.setOnLongClickListener(mOnLongClickListener);
            }
        }

        @Override
        public void onChildViewDetachedFromWindow(View view) {

        }
    };

    private ItemClickSupport(RecyclerView recyclerView) {
        mRecyclerView = recyclerView;
        mRecyclerView.setTag(R.id.item_click_support, this);
        mRecyclerView.addOnChildAttachStateChangeListener(mAttachListener);
    }

    public static ItemClickSupport addTo(RecyclerView view) {
        ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support);
        if (support == null) {
            support = new ItemClickSupport(view);
        }
        return support;
    }

    public static ItemClickSupport removeFrom(RecyclerView view) {
        ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support);
        if (support != null) {
            support.detach(view);
        }
        return support;
    }

    public ItemClickSupport setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
        return this;
    }

    public ItemClickSupport setOnItemLongClickListener(OnItemLongClickListener listener) {
        mOnItemLongClickListener = listener;
        return this;
    }

    private void detach(RecyclerView view) {
        view.removeOnChildAttachStateChangeListener(mAttachListener);
        view.setTag(R.id.item_click_support, null);
    }

    public interface OnItemClickListener {

        void onItemClicked(RecyclerView recyclerView, int position, View v);
    }

    public interface OnItemLongClickListener {

        boolean onItemLongClicked(RecyclerView recyclerView, int position, View v);
    }
}

当你在使用这个工具类的时候需要在 ids.xml文件中定义一个R.id.item_click_support

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="item_click_support" type="id" />
</resources>

代码可以自由使用,法律咨询事宜单击这儿。here
我比较喜欢使用此方法,而不是通过传递OnClickListeners,当然这种情况仅仅是针对item需要处理单击事件。下次你的需求中遇到此类情况,可以考虑使用这个技术。
感谢Mike Wolfson和*Dave Smith *两位作者对本篇文章的校审.

你可以通过Discuss this post on Google+提交你的问题,评论,反馈等.

上一篇下一篇

猜你喜欢

热点阅读