在pressing Android的重复动作和保持一个按钮按钮、动作、pressing、Android

2023-09-12 09:16:33 作者:外向孤独者

我要实现的pressing重复动作并保持一个按钮。例如:当一个按钮用户点击并按住它,它应该一再呼吁在一个固定的时间间隔类似​​的方法,直到用户从按键上移开他的手指。

I want to implement repeat action on pressing and holding a button. Example: When user click on a button and hold it,it should call a similar method again and again on a fixed interval until the user remove his finger from the button.

推荐答案

有多种方法可以做到这一点,但pretty的简单的人会来发布的Runnable 处理程序有一定的延迟。在它的最基本的形式,它看起来有点像这样的:

There are multiple ways to accomplish this, but a pretty straightforward one would be to post a Runnable on a Handler with a certain delay. In it's most basic form, it will look somewhat like this:

Button button = (Button) findViewById(R.id.button);
button.setOnTouchListener(new View.OnTouchListener() {

    private Handler mHandler;

    @Override public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            if (mHandler != null) return true;
            mHandler = new Handler();
            mHandler.postDelayed(mAction, 500);
            break;
        case MotionEvent.ACTION_UP:
            if (mHandler == null) return true;
            mHandler.removeCallbacks(mAction);
            mHandler = null;
            break;
        }
        return false;
    }

    Runnable mAction = new Runnable() {
        @Override public void run() {
            System.out.println("Performing action...");
            mHandler.postDelayed(this, 500);
        }
    };

});

我们的想法是pretty的简单:发布的Runnable 包含在处理程序当重复动作向下的触摸动作发生。在此之后,不要再发布的Runnable ,直到上触摸动作已经过去。该的Runnable 将不断发布自己的处理程序(而向下的触摸动作仍然发生),直到得到的润色作用除去 - 这就是使重复的方面

The idea is pretty simple: post a Runnable containing the repeated action on a Handler when the 'down' touch action occurs. After that, don't post the Runnable again until the 'up' touch action has passed. The Runnable will keep posting itself to the Handler (while the 'down' touch action is still happening), until it gets removed by the touch up action - that's what enables the 'repeating' aspect.

根据不同的按钮,它的OnClick的实际行为/ ontouch你后,你可能想要做的初始后没有延迟。

Depending on the actual behaviour of the button and its onclick/ontouch you're after, you might want to do the initial post without a delay.