如何在Android视图上禁用所有用户输入(点击,触摸)

pat*_*ats 5 user-interface android view android-canvas

我有一个游戏视图,它是View类的扩展。在此视图中,我使用画布绘图对象,用户可以与它们进行交互。

此视图已加载到活动的布局。当在布局中单击按钮时,我想禁用所有用户对游戏视图的输入。

我尝试使用

gameView.setEnabled(false);
gameView.setClickable(false);
Run Code Online (Sandbox Code Playgroud)

但是用户仍然可以与画布对象进行交互。

仅供参考:Gameview类也实现以下接口。

public class Gameview extends View implements OnGestureListener,
        OnDoubleTapListener, OnScaleGestureListener, AnimationListener 
Run Code Online (Sandbox Code Playgroud)

Squ*_*zer 5

你可以这样做:

gameView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }
});
Run Code Online (Sandbox Code Playgroud)

它将捕获所有用户输入,如果返回true,则将在此处停止。如果返回false,则将假定您尚未处理事件并将其传递给下一个侦听器。当需要启用/禁用视图时,可以将布尔变量设置为true / false。


Bir*_*dia 5

在您的GameView中实现这样的onTouchEvent()。

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
    }



}
Run Code Online (Sandbox Code Playgroud)

如何使用?

gameView.setTouchable(false); // to disable touch

gameView.setTouchable(true); // to enable touch
Run Code Online (Sandbox Code Playgroud)