如何在用户仍然按住Android

时间:2016-12-12 21:27:08

标签: android listener android-button ontouchlistener motionevent

所以我试图在按钮上显示自用户开始按下它以来的时间,这是我的代码:

btn.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            long eventDuration;

            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isDown = true;
                    break;
                case MotionEvent.ACTION_UP:
                    isDown = false;
                    break;
                default:
                    break;
            }
            eventDuration = motionEvent.getEventTime() - motionEvent.getDownTime();
            btn.setText(String.valueOf(eventDuration));
            return true;

        }

    });

代码正常工作,但是如果用户按住按钮而没有移动他的手指因为没有动作(例如“MotionEvent.ACTION_HOLD”),则按下的时间值不会更新。即使用户没有移动他的手指,我希望该值能够不断更新。

每次Action都是“MotionEvent.ACTION_DOWN”

时,我试图运行一个方法
while(isDown){
    eventDuration = motionEvent.getEventTime() - motionEvent.getDownTime();
                    btn.setText(String.valueOf(eventDuration));
    }

但是没有工作,while循环不会停止并且isDown保持其最后一个值true。任何人都可以告诉我如何让它工作?谢谢!

2 个答案:

答案 0 :(得分:1)

您可以在此处使用CountDownTimer,当用户按下按钮时,启动countDownTimer,其最大限制值非常高,并在ouTouchListener

中收到action_up时取消它
int TICK_DURATION = 1000;
int MAX_LIMIT_IN_MILLISECONDS = Integer.MAX_VALUE;
CountDownTimer cdt = new CountDownTimer(MAX_LIMIT_IN_MILLISECONDS, TICK_DURATION) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds spent: " + (MAX_LIMIT_IN_MILLISECONDS-millisUntilFinished) / 1000);
       //here you can have your logic to set text to edittext
    }

    public void onFinish() {
        // this will be called when max int value is reached!! depending upon your requirement you can restart countdownTimer here
    }

}

然后启动这个内部Action_down尚未启动,否则重置它

cdt.start();

并在action_down内完成

cdt.cancel();

答案 1 :(得分:0)

您需要使用计时器

private int timeDown;
private TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        //update
    }
};
private Timer timer;

然后在onTouch事件中,启动Timer

btn.setOnTouchListener(new View.OnTouchListener(){

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

        long eventDuration;

        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isDown = true;
                if(timer == null){
                   timer = new Timer();
                   int updateFrequency = 1000; // every second
                   timeDown = motionEvent.getDownTime();
                   timer.scheduleAtFixedRate(timerTask, 0, updateFrequency);
                }
                break;
            case MotionEvent.ACTION_UP:
                isDown = false;
                timer.cancel();
                timer = null;
                break;
            default:
                break;
        }
        return true;

    }

});