How to display the timer in android

2019-01-24 11:54发布

问题:

I want to display the timer in TextView in the format of like [ 19:59].so when i click the start button ,the timer will display like this for example,i want to set upto 20 mintues,it will display like [19:58][19:87].can anyone give some ideas or example code?

回答1:

package com.example.testproject;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {

    public int seconds = 60;
    public int minutes = 10;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Declare the timer
        Timer t = new Timer();
        //Set the schedule function and rate
        t.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        TextView tv = (TextView) findViewById(R.id.main_timer_text);
                        tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
                        seconds -= 1;

                        if(seconds == 0)
                        {
                            tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));

                            seconds=60;
                            minutes=minutes-1;

                        }



                    }

                });
            }

        }, 0, 1000);
    }

}


回答2:

You can use the CountDownTimer.

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

     TextView _tv = (TextView) findViewById( R.id.textView1 );
    new CountDownTimer(20*60000, 1000) {

        public void onTick(long millisUntilFinished) {
            _tv.setText("seconds remaining: " +new SimpleDateFormat("mm:ss:SS").format(new Date( millisUntilFinished)));
        }

        public void onFinish() {
           _tv.setText("done!");
        }
     }.start();

To cancel just call cancel on the timer.

public final void cancel()

Cancel the countdown.



回答3:

  //start button click
     CountDown timer = new CountDown(180000, 1000);
     timer.start();

//stop button click
timer.stop();   

    //countdown class
    public class CountDown extends CountDownTimer {

          public CountDown(long millisInFuture, long countDownInterval) {
             super(millisInFuture, countDownInterval);
          }

          @Override
          public void onTick(long millisUntilFinished) {
             long ms = millisUntilFinished;
             String text = String.format("%02d\' %02d\"",
                                         TimeUnit.MILLISECONDS.toMinutes(ms) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(ms)),
                                         TimeUnit.MILLISECONDS.toSeconds(ms) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(ms)));
             textViewTimer.setText(text);
          }

          @Override
          public void onFinish() {
             textViewTimer.setText("ffinish");
          }
       }


回答4:

This can be done using cronometer, the most main reason is supporting API 1+, which is quite impressive rather than TextClock, which supports API 17+.

You can do lots of other things with cronometer. for example you can set start time in it

chronometer.setBase(SystemClock.elapsedRealtime());

You can also learn about it more here.



回答5:

Here I have use Timer class to display timer

    public class FourthActivity extends AppCompatActivity {
    Button startButton, pauseButton;
    TextView timerValue;
    Timer timer;
    int seconds = 0, minutes = 0, hour = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fourth);
        bindView();

        timer = new Timer();
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.scheduleAtFixedRate(new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (seconds == 60) {
                                    timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
                                    minutes = seconds / 60;
                                    seconds = seconds % 60;
                                    hour = minutes / 60;
                                }
                                seconds += 1;
                                timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
                            }
                        });
                    }
                }, 0, 1000);
            }
        });
    }

    private void bindView() {
        timerValue = (TextView) findViewById(R.id.timerValue);
        startButton = (Button) findViewById(R.id.startButton);
    }
}

In layout, there are one TextView and one Button to start timer. I have use Timer class method scheduleAtFixedRate. Time will be displayed in hh:mm:ss form.



回答6:

do it this way activity_timer.xml

<android.support.v7.widget.LinearLayoutCompat
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <Chronometer
            android:id="@+id/chronometer2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


    </android.support.v7.widget.LinearLayoutCompat>

And in Activity

public class TimerActivity extends AppCompatActivity {
   private Chronometer chronometer2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timer);

        chronometer2 = findViewById(R.id.chronometer2);
        chronometer2.start();
    }
}

You can also use stop

chronometer2.stop();

Re Start

chronometer2.setBase(SystemClock.elapsedRealtime());
 chronometer2.start();