简体   繁体   中英

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

I'm trying to implement a decreasing counter using for loop in android java. I have used handler & runnable to delay for loop iteration and I want the counter to start from 80 and end on 0, but in output, I'm getting counter from 0 to 80. In short, the reverse is required.

This is my code,

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);
        }

Current output => Start from 0 & end on 80

Required output => Start from 80 & end on 0

Try this:

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);

Also I would recommend using log tags rather than system.println for android

You can user CountDownTimer as:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM