有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java理解为什么在onDispatchTouchEvent()返回True后仍调用onClick()

比如说,在Android应用程序中,我们希望能够在任何时候暂时可靠地忽略所有用户触摸

根据我对堆栈溢出以及hereherehere所做的研究,一致同意的解决方案似乎是这样的:

(MainActivity.java的代码):

// returning true should mean touches are ignored/blocked
@Override
public boolean dispatchTouchEvent(MotionEvent pEvent) {

    if (disableTouches) {
        return true;
    } else {
        return super.dispatchTouchEvent(pEvent);
    }

}

然而,当我们引入Android Monkey Exerciser Tool并以快速的速度向应用程序发送触摸事件时,很明显,猪开始在量子级别飞行——即使在“BlockTouchs”设置为true之后/期间,我们也可以接到对onClick()的呼叫

我的问题是:这是为什么?——这是安卓的正常行为,还是我在代码中犯了错误?:)

注意:我已经排除了onClick()被用户输入而不是触摸调用的可能性(因此不受onDispatchTouchEvent()方法的控制)。。。通过在monkey命令中添加“-pct touch 100”

以下是我在测试中使用的代码:

主要活动:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    View rootView; // turns black when "touch rejection" is in progress

    View allowedButton;
    View notAllowedButton;

    // Used to decide whether to process touch events.
    // Set true temporarily when notAllowedButton is clicked.
    boolean touchRejectionAnimationInProgress = false;

    int errorCount = 0; // counting "unexpected/impossible" click calls

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rootView = findViewById(R.id.rootView);

        allowedButton = findViewById(R.id.allowedButton);
        notAllowedButton = findViewById(R.id.notAllowedButton);

        allowedButton.setOnClickListener(this);
        notAllowedButton.setOnClickListener(this);

        allowedButton.setBackgroundColor(Color.GREEN);
        notAllowedButton.setBackgroundColor(Color.RED);

    }

    // returning true should mean touches are ignored/blocked
    @Override
    public boolean dispatchTouchEvent(MotionEvent pEvent) {

        if (touchRejectionAnimationInProgress) {
            Log.i("XXX", "touch rejected in dispatchTouchevent()");
            return true;
        } else {
            return super.dispatchTouchEvent(pEvent);
        }

    }

    @Override
    public void onClick(View viewThatWasClicked){

        Log.i("XXX", "onClick() called.  View clicked: " + viewThatWasClicked.getTag());

        //checking for unexpected/"impossible"(?) calls to this method
        if (touchRejectionAnimationInProgress) {
            Log.i("XXX!", "IMPOSSIBLE(?) call to onClick() detected.");
            errorCount ++;
            Log.i("XXX!", "Number of unexpected clicks: " + errorCount);
            return;
        } // else proceed...

        if (viewThatWasClicked == allowedButton) {
            // Irrelevant
        } else if (viewThatWasClicked == notAllowedButton) {
            // user did something that is not allowed.
            touchRejectionAnimation();
        }

    }

    // When the user clicks on something "illegal,"
    // all user input is ignored temporarily for 200 ms.
    // (arbitrary choice of duration, but smaller is better for testing)
    private void touchRejectionAnimation() {

        Log.i("XXX", "touchRejectionAnimation() called.");

        touchRejectionAnimationInProgress = true;
        rootView.setBackgroundColor(Color.BLACK);

        // for logging/debugging purposes...
        final String rejectionID = (new Random().nextInt() % 9999999) + "";
        Log.i("XXX", "rejection : " + rejectionID + " started.");

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try { Thread.sleep(200); } catch (Exception e) {
                    Log.e("XXX", "exception in touchRejection() BG thread!");
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("XXX", "rejection " + rejectionID + " ending");
                        rootView.setBackgroundColor(Color.WHITE);
                        touchRejectionAnimationInProgress = false;
                    }
                });
            }
        });

        thread.start();

    }

}

布局。xml:

<?xml version="1.0" encoding="utf-8"?>
<安卓.support.constraint.ConstraintLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:id="@+id/rootView"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    tools:context=".MainActivity">

    <View
        安卓:id="@+id/allowedButton"
        安卓:layout_width="0dp"
        安卓:layout_height="0dp"
        安卓:layout_marginTop="32dp"
        安卓:layout_marginBottom="32dp"
        安卓:tag="allowedButton"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/notAllowedButton"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        安卓:id="@+id/notAllowedButton"
        安卓:layout_width="0dp"
        安卓:layout_height="0dp"
        安卓:layout_marginTop="32dp"
        安卓:layout_marginBottom="32dp"
        安卓:tag="view2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/allowedButton"
        app:layout_constraintTop_toTopOf="parent" />

</安卓.support.constraint.ConstraintLayout>

共 (1) 个答案

  1. # 1 楼答案

    如果不想在任何视图上触发onClick(),请单击

    以下是需要注意的步骤

    Create custom viewGroup eg: MyConstraintLayout and add all child inside it.

    Override onInterceptTouchEvent(MotionEvent ev) and return it has true.

    public class MyConstraintLayout extends ConstraintLayout {
    
        private boolean mIsViewsTouchable;
    
        public ParentView(Context context) {
            super(context);
        }
    
        public ParentView(Context context, AttributeSet attrs) {
            super(context, attrs);
            inflate(context, R.layout.custom_view, this);
        }
    
        public ParentView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        public void setViewsTouchable(boolean isViewTouchable) {
            mIsViewsTouchable = isViewTouchable;
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            return mIsViewsTouchable;
        }
     }
    

    注意:根据需要使用setViewsTouchable()方法,如果将参数传递为true,则所有视图都不可单击;如果为false,则视图都可单击