问题描述
我跟RecyclerView取代我的ListView,列表,显示不错,但我想知道如何获得点击的项目和它的位置,类似的方法OnItemClickListener.onItemClick(AdapterView父母,视图V,INT位置,长ID)我们在ListView中使用。
I am replacing my ListView with RecyclerView, list showing ok, but I would like to know how to get clicked item and its position, similar to the method OnItemClickListener.onItemClick(AdapterView parent, View v, int position, long id) we use in ListView.
感谢您的想法!
推荐答案
根据链接:Why不RecyclerView有onItemClickListener()?而如何RecyclerView从列表视图不同,并且还@邓肯的总体思路,我给我的解决方案在这里?
Based on the link: Why doesn't RecyclerView have onItemClickListener()? and How RecyclerView is different from Listview?, and also @Duncan's general idea, I give my solution here:
-
定义一个接口RecyclerViewClickListener传递消息适配器到活动/片段:
define one interface 'RecyclerViewClickListener' for passing message from adapter to Activity/Fragment:
public interface RecyclerViewClickListener
{
public void recyclerViewListClicked(View v, int position);
}
在活动/片段实现接口,并且还通过侦听器适配器:
In Activity/Fragment implement the interface, and also pass listener to adapter:
@Override
public void recyclerViewListClicked(View v, int position){... ...}
//set up adapter and pass clicked listener this
myAdapter = new MyRecyclerViewAdapter(context, this);
在适配器和ViewHolder:
In Adapter and ViewHolder:
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ItemViewHolder> {
... ...
private Context context;
private static RecyclerViewClickListener itemListener;
public MyRecyclerViewAdapter(Context context, RecyclerViewClickListener itemListener) {
this.context = context;
this.itemListener = itemListener;
... ...
}
//ViewHolder class implement OnClickListener,
//set clicklistener to itemView and,
//send message back to Activity/Fragment
public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
... ...
public ItemViewHolder(View convertView)
{
super(convertView);
... ...
convertView.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
itemListener.recyclerViewListClicked(v, this.getPosition());
}
}
}
经过测试,它工作正常。
After testing, it works fine.
[更新]
由于API 22, RecyclerView.ViewHoler.getPosition()
是pcated,所以不是用 getLayoutPosition()去$ P $
。
Since API 22, RecyclerView.ViewHoler.getPosition()
is deprecated, so instead with getLayoutPosition()
.
这篇关于点击获取项目及其RecyclerView位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!