Android Countdown Timer to Date

前端 未结 7 1890
死守一世寂寞
死守一世寂寞 2020-12-14 11:34

I am trying to make a countdown timer for a game/date in android. I want to create a timer that displays the days, hours, minutes, and seconds to a date I specify with a fin

7条回答
  •  孤街浪徒
    2020-12-14 12:00

    Here is an Android built-in CountDownTimer that will display the time formatted to your days, hours, minutes, and seconds all in a TextView:

    public class Example extends Activity {
        CountDownTimer mCountDownTimer;
        long mInitialTime = DateUtils.DAY_IN_MILLIS * 2 + 
                            DateUtils.HOUR_IN_MILLIS * 9 +
                            DateUtils.MINUTE_IN_MILLIS * 3 + 
                            DateUtils.SECOND_IN_MILLIS * 42;
        TextView mTextView;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            mTextView = (TextView) findViewById(R.id.empty);
    
            mCountDownTimer = new CountDownTimer(mInitialTime, 1000) {
                StringBuilder time = new StringBuilder();
                @Override
                public void onFinish() {
                    mTextView.setText(DateUtils.formatElapsedTime(0));
                    //mTextView.setText("Times Up!");
                }
    
                @Override
                public void onTick(long millisUntilFinished) {
                    time.setLength(0);
                     // Use days if appropriate
                    if(millisUntilFinished > DateUtils.DAY_IN_MILLIS) {
                        long count = millisUntilFinished / DateUtils.DAY_IN_MILLIS;
                        if(count > 1)
                            time.append(count).append(" days ");
                        else
                            time.append(count).append(" day ");
    
                        millisUntilFinished %= DateUtils.DAY_IN_MILLIS;
                    }
    
                    time.append(DateUtils.formatElapsedTime(Math.round(millisUntilFinished / 1000d)));
                    mTextView.setText(time.toString());
                }
            }.start();
        }
    }
    

提交回复
热议问题