为什么我的图像不会通过 onTick() 方法每 1 秒更改一次?

Why is my image not changing every 1 second by the onTick() method?

问题:图像发生变化,但不是在适当的时间。

特此CountDownTimerclass参考:

CountDownTimer

Schedule a countdown until a time in the future, with regular notifications on intervals along the way.

Public Constructors

CountDownTimer(long millisInFuture, long countDownInterval)

millisInFuture The number of millis in the future from the call to start() until the countdown is done and onFinish() is called.

countDownInterval The interval along the way to receive onTick(long) callbacks.

Source: http://developer.android.com/reference/android/os/CountDownTimer.html

假设我有以下两张图片:

而且我想每 1 秒在它们之间切换一次,

我做错了什么?有人可以给我指路吗?

    blinkingAlarm = new CountDownTimer(1000,1000) {

    boolean switchImage = false;

    @Override
    public void onTick(long millisUntilFinished) {


        if(!switchImage)
        {
            button1.setBackgroundResource(R.drawable.image1);
        }
        else if(switchImage)
        {
            button1.setBackgroundResource(R.drawable.image2);           
        }

        // Flip
        switchImage = (!switchImage);

    }


    @Override
    public void onFinish() {    

        // Loop
        blinkingAlarm.start();
    }
};

方法正在被调用

    @Override
    public void onClick(View v) {

        switch(v.getId())
        {

        case R.id.button1:  
            blinkingAlarm.start();
        break;

        }

}

只需使用处理程序和 postDelayed 而不是 CountDownTimer。 在你的 class 添加这个变量:

private boolean switchImage = false;
private Handler handler;

然后使用此代码:

handler = new Handler();

Runnable changeImage = new Runnable() {
        @Override
        public void run() {
            if(!switchImage){
                button1.setBackgroundResource(R.drawable.image1);
                switchImage = true;
            } else {
                button1.setBackgroundResource(R.drawable.image2);
                switchImage = false;
            }
            handler.postDelayed(this, 1000);
        }
    };

    handler.postDelayed(changeImage, 1000);