Android 模拟点击

imageView.setOnClickListener(v -> {
i++;
textView.setText("===" + i);
});

    button.setOnClickListener(v -> {
        i++;
        imageView.performClick();

    });

    button1.setOnClickListener(v -> {
        i++;
        Log.e("MainActivity", "btn1");
        long downTime = SystemClock.uptimeMillis();
        long eventTime = SystemClock.uptimeMillis() + 100;
        float upX = imageView.getX() + 50; //随机生成
        float upY = imageView.getY() + 50;
        MotionEvent obtainDown = MotionEvent.obtain(downTime, eventTime, ACTION_DOWN, upX, upY, 0);

        long downTime1 = SystemClock.uptimeMillis();
        long eventTime1 = SystemClock.uptimeMillis() + 100;
        float upX1 = imageView.getX() + 50;
        float upY1 = imageView.getY() + 50;
        MotionEvent obtainUp = MotionEvent.obtain(downTime1, eventTime1, MotionEvent.ACTION_UP, upX1, upY1, 0);
        imageView.dispatchTouchEvent(obtainDown);
        imageView.dispatchTouchEvent(obtainUp);
        obtainDown.recycle();
        obtainUp.recycle();
        Log.e("MainActivity", "downTime:" + downTime + " ,eventTime:" + eventTime + " ,upX:" + upX + " ,upY:" + upY + " ,downTime1:" + downTime1 + " ,eventTime1:" + eventTime1 + " ,upX1:" + upX1 + " ,upY1:" + upY1);
    });

你可能感兴趣的:(Android 模拟点击)