我一直在尝试按照以下指南在RecyclerView上实现onClickListener
http://blog.lovelyhq.com/creating-lists-with-recyclerview-in-android-part-2/
但是,我似乎无法获得调用setOnClickListener或getPosition的任何上下文。
这是我的代码(错误旁边有评论):
public class CategoryDataAdapter extends RecyclerView.Adapter<CategoryDataAdapter.DataViewHolder> implements View.OnClickListener
{
private List<CategoryData.Category> dataList;
private static Context con;
private ClickListener clickListener;
public CategoryDataAdapter(Context context, List<CategoryData.Category> list)
{
this.dataList = list;
con = context;
}
@Override
public int getItemCount()
{
return dataList.size();
}
@Override
public void onBindViewHolder(DataViewHolder dataViewHolder, int i)
{
CategoryData.Category item = dataList.get(i);
Picasso.with(con).load(item.getImage()).into(dataViewHolder.categoryImage);
dataViewHolder.categoryText.setText(item.getName());
}
@Override
public DataViewHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.tile_category, viewGroup, false);
DataViewHolder dvh = new DataViewHolder(itemView);
return dvh;
}
public static class DataViewHolder extends RecyclerView.ViewHolder
{
protected ImageView categoryImage;
protected TextView categoryText;
public DataViewHolder(View v)
{
super(v);
categoryImage = (ImageView) v.findViewById(R.id.categoryImage);
categoryText = (TextView) v.findViewById(R.id.categoryName);
v.setOnClickListener(this); // here, can't put in 'this'
}
}
public interface ClickListener
{
/**
* Called when the view is clicked.
*
* @param v view that is clicked
* @param position of the clicked item
* @param isLongClick true if long click, false otherwise
*/
public void onClick(View v, int position, boolean isLongClick);
}
public void setClickListener(ClickListener clickListener)
{
this.clickListener = clickListener;
}
@Override
public void onClick(View v)
{
clickListener.onClick(v, getPosition(), false); // here, get position
}
}
我该怎么做才能解决这个问题?我只需要整个视图的点击监听器,而不是一个特定的项目(已经实现了)
答案 0 :(得分:4)
不要让RecyclerView.Adapter
实施View.OnClickListener
,而是让DataViewHolder
实现这一点。然后还将rootview保存在DataViewHolder变量(如ImageView和TextView)上,并在onBindViewHolder
使用如下内容:
dataViewHolder.rootView.setOnClickListener(dataViewHolder);
答案 1 :(得分:0)
在recyclerAdapter中添加用于检测点击侦听器的界面
public class DeviceAdapter extends ArrayAdapter<Blablah>{
private OnClickItemListener listener;
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
................
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(listener != null){
listener.click(int position)
}
}
});
.............
return convertView;
}
public interface OnClickItemListener {
public void click(int position);
}
public void setOnClickItemListener(OnClickItemListener listener) {
this.listener = listener;
}
}
并将适配器侦听器设置为您的片段/活动
adapterRecycler.setOnsetOnClickItemListener(new ....{
});