如何使用for循环在textView.setText中实现递减计数器?

How to implement decreasing counter in textView.setText using for loop?

我正在尝试在 android java 中使用 for 循环实现递减计数器。我已经使用 handler & runnable 来延迟循环迭代,我希望计数器从 80 开始并以 0 结束,但在输出中,我得到的计数器从 0 到 80。简而言之,需要反过来。

这是我的代码,

TextView totalpoints = (TextView) findViewById(R.id.txttotalpoints);
        Handler handler1 = new Handler();

        for (int count = 80;count>=0; count--){
            int finalCount = count;


            handler1.postDelayed(new Runnable() {

                @Override
                public void run() {
                    totalpoints.setText("Total Points : "+ finalCount);
                    System.out.println("This is in newpointsCounter" + finalCount);


                }
                }, 1000 * count);
        }

当前输出 => 从 0 开始并在 80 结束

所需输出 => 从 80 开始并在 0 结束

试试这个:

final Handler handler = new Handler(); 
int count = 80;

final Runnable runnable = new Runnable() {
    public void run() { 
        totalpoints.setText("Total Points : " + count);
        Log.d(TAG, "count: " + count);
        if (count-- > 80) {
            handler.postDelayed(this, 5000);
        }
    } 
}; 

handler.post(runnable);

此外,我建议使用日志标签而不是 system.println 用于 android

您可以将 CountDownTimer 用作:

CountDownTimer countDownTimer = new CountDownTimer(80000, 1000) {
    @Override
    public void onTick(long millisUntilFinished) {
        //TODO on each  interval, print your count
    }

    @Override
    public void onFinish() {
        //TODO on finish of timer, you will get notified
    }
};

countDownTimer.start();
No need to use handler, Android provides CountDownTimer itself just use it.


// For Java

    new CountDownTimer(30000, 1000) {
    
        public void onTick(long millisUntilFinished) {
            
                System.out.println( millisUntilFinished / 1000)
        }
    
        public void onFinish() {
            //work done
        }
    
    }.start();


// For kotlin

object : CountDownTimer(30000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
            System.out.println( millisUntilFinished / 1000)
            }

            override fun onFinish() {
            }
        }.start()