Parent click event not firing when recyclerview clicked
There is a better solution. That is, subclass your CardView
:
public class InterceptTouchCardView extends CardView {
public InterceptTouchCardView(Context context) {
super(context);
}
public InterceptTouchCardView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public InterceptTouchCardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* Intercept touch event so that inner views cannot receive it.
*
* If a ViewGroup contains a RecyclerView and has an OnTouchListener or something like that,
* touch events will be directly delivered to inner RecyclerView and handled by it. As a result,
* parent ViewGroup won't receive the touch event any longer.
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
}
In my case, I had a CardView with a couple of buttons and a RecyclerView. With the solutions of ywwynm and Daryl the problem was that the CardView would intercept the events from all of its children views, including the buttons. But what I wanted was for the CardView to intercept the touch events of the RecyclerView only. My solution was the following:
public class UntouchableRecyclerView extends RecyclerView {
public UntouchableRecyclerView(Context context) {
super(context);
}
public UntouchableRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public UntouchableRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
return false;
}
}
I figured out how to get the click event to the RecyclerView's parent. My solution kind of feels like a hack, so I'm hoping that someone can come up with a better solution.
In the RecylerView.Adapter:
@Override
public ViewHolder onCreateViewHolder(final ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.my_item_layout, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(view);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewGroup.callOnClick();
}
});
viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return viewGroup.performLongClick();
}
});
return viewHolder;
}
I then had to hook up the click event on the RecyclerView:
RecyclerView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
parentView.callOnClick();
}
});
RecyclerView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return parentView.performLongClick();
}
});
recyclerView.setLayoutFrozen(true);
just setLayoutFrozen true after setAdapter for recyclerView