简体   繁体   中英

Android - TextView with dynamic text

For a simple Timer App I try to add a TextView to my app that says something like "15 seconds remaining", obviously this changes every seccond until it finally changes to "time up!". My idea was to use a loop like this:

while(now<endTime):
    remaining=endTime-now;
    text.setText(remaining);

While this could work, I am unsure if this is the right approach or if theres a better option.

Use a CountDownTimer, instead.

I use this code snippet to achive a similar result:

    final int secs = 5;
    new CountDownTimer((secs +1) * 1000, 1000) // Wait 5 secs, tick every 1 sec
    {
        @Override
        public final void onTick(final long millisUntilFinished)
        {
            txtCount.setText("" + (int) (millisUntilFinished * .001f));
        }
        @Override
        public final void onFinish()
        {
            txtCount.setText("GO!");
        }
    }.start();

In the onFinish() handler you can do the "elapsed time" stuff

You can use a handler to do it as below:

Handler myHandler=new Handler();
    myHandler.postDelayed(timer, 1000);

    private Runnable timer= new Runnable() {
    public void run() {
    if(counter==15){
      textview.setText("Time Up");
      counter=0;
    }
    else{
        counter++;
        textview.setText(counter+ " remaining");}
        }
    };

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