RecyclerView的onClick [英] RecyclerView onClick

查看:193
本文介绍了RecyclerView的onClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有使用 RecyclerView 找到了一种方法来设置 onClickListener 来的物品任何人 RecyclerView ? 我想到了一个监听器设置每个布局的每个项目,但似乎有点太麻烦 我敢肯定有一种方法为 RecyclerView 来侦听的onClick 事件,但我不能完全数字出来。

Has anyone using RecyclerView found a way to set an onClickListener to items in the RecyclerView? I thought of setting a listener to each of the layouts for each item but that seems a little too much hassle I'm sure there is a way for the RecyclerView to listen for the onClick event but I can't quite figure it out.

推荐答案

请参阅雅各回答了更多的去耦解决方案,使用<一个href="https://developer.android.com/reference/android/support/v7/widget/RecyclerView.OnItemTouchListener.html">RecyclerView#OnItemTouchListener.

Please see Jacob's answer for a more decoupled solution, using RecyclerView#OnItemTouchListener.

随着API的从根本上改变,它不会让我感到吃惊,如果你要创建一个 OnClickListener 为每个项目。这是不是太大的麻烦,虽然。在你实施 RecyclerView.Adapter&LT; MyViewHolder&GT; ,你应该有:

As the API's have radically changed, It wouldn't surprise me if you were to create an OnClickListener for each item. It isn't that much of a hassle though. In your implementation of RecyclerView.Adapter<MyViewHolder>, you should have:

private final OnClickListener mOnClickListener = new MyOnClickListener();

@Override
public MyViewHolder onCreateViewHolder(final ViewGroup parent, final int position) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.myview, parent, false);
    view.setOnClickListener(mOnClickListener);
    return new MyViewHolder(view);
}

的onClick 方法:

@Override
public void onClick(final View view) {
    int itemPosition = mRecyclerView.getChildPosition(view);
    String item = mList.get(itemPosition);
    Toast.makeText(mContext, item, Toast.LENGTH_LONG).show();
}


请注意,这仍然是在preVIEW,这样的API的可以的变化。


Note that this is still in preview, so API's may change.

这篇关于RecyclerView的onClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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