Android: How to prevent any touch events from being passed from a view to the one underneath it?
Add an onTouchEvent
method to the view with top position then return true. True will tell the event bubbling that the event was consumed therefore prevent event from bubbling to other views.
protected boolean onTouchEvent (MotionEvent me) {
return true;
}
For v1
you would do an import:
import android.view.View.OnTouchListener;
Then set the onTouchListener:
v1.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
From code
View v1 = new View(this);
v1.setClickable(true);
v1.setFocusable(true);
OR
From xml
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My button"
android:focusable="true"
android:clickable="true"/>
This will prevent touch and click events from being propagated to views that stay below your view.
Or if you inflate the View then to .xml add android:clickable="true"
You can do this too. You can set touch listener to child view and then in onTouch()
event, you can block intercept touch event
of parent.
i.e.
View v = findViewById(R.id.sample_view);
v.setOnTouchListener(new OnTouchListener() {
// Setting on Touch Listener for handling the touch inside ScrollView
@Override
public boolean onTouch(View v, MotionEvent event) {
// Disallow the touch request for parent scroll on touch of child view
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});