首页 > 解决方案 > 如何在android中创建倒计时onClickListener

问题描述

该场景就像用户触摸视图并保持该视图指定的秒数。类似于长焦点侦听器但具有指定计时器的东西,如果用户在计时器之前将手指移开,那么它将不会调用操作。是否可以?请指导。

标签: androidlistener

解决方案


public class MainActivity extends Activity {
// This example shows an Activity, but you would use the same approach if
// you were subclassing a View.
//Declare timer
CountDownTimer cTimer = null;    
@Override
public boolean onTouchEvent(MotionEvent event){

    int action = MotionEventCompat.getActionMasked(event);

    switch(action) {
        case (MotionEvent.ACTION_DOWN) :
            startTimer();
            Log.d(DEBUG_TAG,"Action was DOWN");
            return true;
        case (MotionEvent.ACTION_UP) :
            cancelTimer();
            Log.d(DEBUG_TAG,"Action was UP");
            return true;
        default :
            return super.onTouchEvent(event);
    }

void startTimer() {
    cTimer = new CountDownTimer(30000, 1000) {
        public void onTick(long millisUntilFinished) {
            //you can keep updating the ui here.
        }
        public void onFinish() {
            //this is where you want to do something on the basis on long tap action.
        }
    };
    cTimer.start();
}
void cancelTimer() {
    if(cTimer!=null)
        cTimer.cancel();
}
}

您可以在文档中查看 MotionEvents 。


推荐阅读