如何在用户仍然按住 android 时获取按下按钮的时间

How to get the time a button is pressed while user still holding down in android

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

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。谁能告诉我如何让它工作?谢谢!

您需要使用定时器

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

然后在你的 onTouch 事件中,启动定时器

btn.setOnTouchListener(新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;

    }

});

您可以在此处使用 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();