How to disable all user inputs (click, touch) on an android view
Solution 1
In your GameView implement onTouchEvent() like this.
public class GameView extends View {
public boolean isTouchable() {
return isTouchable;
}
public void setTouchable(boolean isTouchable) {
this.isTouchable = isTouchable;
}
private boolean isTouchable= true;
public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GameView(Context context) {
super(context);
}
//// ... Your Code
@Override
public boolean onTouchEvent(MotionEvent event) {
if(isTouchable){
return super.onTouchEvent(event); // Enable touch event
}
return false; // Block touch event
}
}
How to use?
gameView.setTouchable(false); // to disable touch
gameView.setTouchable(true); // to enable touch
Solution 2
You can do this:
gameView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
It will capture all user input, and if you return true, it will stop here. If you return false it will assume that you have not handled the event and pass it on to the next listener. You can have a boolean variable that you set to true / false when you need to enable / disable your view.
Solution 3
Kotlin:
val yourView: View = findViewById(R.id.yourViewId)
// disable user interaction
yourView.setOnTouchListener { _, _ -> false }
// enable user interaction
yourView.setOnTouchListener { v, event -> v.onTouchEvent(event) }
pats
Updated on June 14, 2022Comments
-
pats almost 2 years
I have a game view which is an extension of View class. In this view I use canvas drawing objects, which the users can interact with.
This view loaded to the layout of an activity. I want to disable all user inputs to the game view, when a button is clicked in the layout.
I tried using
gameView.setEnabled(false); gameView.setClickable(false);
But still the user can interact with the canvas objects.
FYI : Gameview class implements following interfaces as well.
public class Gameview extends View implements OnGestureListener, OnDoubleTapListener, OnScaleGestureListener, AnimationListener