美文网首页
简单的倒计时 - Android

简单的倒计时 - Android

作者: NicholasHwang | 来源:发表于2019-10-11 22:38 被阅读0次
    CountDownActivity.java
    import android.os.Bundle;
    import android.os.Handler;
    import android.widget.TextView;
    import androidx.appcompat.app.AppCompatActivity;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    import cn.com.smarthome.utils.DateHelper;
    
    public class CountDownActivityextends AppCompatActivity {
    
      private TextViewmTvCountDown;
    
      private long mExpectTime;
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_count_down);
          initView();
          initData();
          initCountDown();
      }
    
      private void initView() {
          mTvCountDown = findViewById(R.id.tv_countdown);
      }
    
      private void initData() {
          String dateStr = "2019-10-28 10:45";
          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.CHINA);
          try {
              Date desDate = simpleDateFormat.parse(dateStr);
              Date curDate = new Date();
              if (desDate != null) {
                  mExpectTime = (desDate.getTime() - curDate.getTime()) / 1000;
              }
          } catch (ParseException e) {
              e.printStackTrace();
          }
      }
      Handler handler = new Handler();
      private void initCountDown() {
          Runnable runnable = new Runnable() {
              @Override
              public void run() {
                  mExpectTime = mExpectTime - 1;
                  mTvCountDown.setText(DateHelper.getDateStr(mExpectTime));
                  handler.postDelayed(this,1000);
              }
          };
          handler.postDelayed(runnable,1000);
      }
    }
    
    DateHelper.java
    public class DateHelper {
        public static String getDateStr(long seconds) {
          if (seconds <= 0) {
              return "00天00时00分00秒";
           }
          long day = seconds / (60 * 60 * 24);
          long hour = (seconds % (60 * 60 * 24)) / (60 *60);
          long minute = ((seconds % (60 * 60 * 24)) % (60 *60)) / 60;
          long second = ((seconds % (60 * 60 * 24)) % (60 *60)) % 60;
          return (day > 9 ? day : "0" + day) + "天" +
                    (hour > 9 ? hour : "0" + hour) + "时" +
                    (minute > 9 ? minute : "0" + minute) + "分" +
                    (second > 9 ? second : "0" + second) + "秒";
        }
    }
    

    代码有些粗糙,凑合着看吧

    相关文章

      网友评论

          本文标题:简单的倒计时 - Android

          本文链接:https://www.haomeiwen.com/subject/lxcfmctx.html