我在带有cardview的recyclerview上发现了这个教程但是我无法添加onitemclick监听器..我想点击这些项目并转到另一个活动。请帮我。将受到高度赞赏。 谢谢
http://pulse7.net/android/how-to-use-recyclerview-with-cardview-in-android-application/
答案 0 :(得分:1)
这可以轻松完成:
在ViewHolder类中:
.
.
...
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView cardimage;
TextView cardtitle;
Flower Flower;
public ViewHolder(View itemView) {
super(itemView);
cardimage = (ImageView) itemView.findViewById(R.id.cardimage);
cardtitle = (TextView) itemView.findViewById(R.id.cardtitle);
}
}
放入构造函数,(在超级(...)调用之后):
itemView.setOnClickListener(new CardOnClickListener());
在任何你想要的地方创建这个类
class CardOnClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
// TODO Handle item click
Log.e("Clicked !!!");
}
}
我之前已经阅读过更好的方法,但我喜欢这种方式很容易而且不复杂。
答案 1 :(得分:0)
您可以使用侦听器创建自己的类
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null) {
mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View childView = rv.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, rv.getChildAdapterPosition(childView));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public static interface OnItemClickListener {
public void onItemClick(View view, int position);
public void onItemLongClick(View view, int position);
}
}
然后在您的回收视图中:
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
// click
}
@Override
public void onItemLongClick(View view, int position) {
// long click
}
}));
@Abhinav Puri的回答是正确的,但我写了这个解决方案以备你想要并长按一下。