Android使用Handler实现倒计时功能

2020-11-05 09:50:03 浏览数 (1)

本文实例为大家分享了Android实现倒计时功能的具体代码,供大家参考,具体内容如下

1、实现效果

如下图所示:

2、代码实现

新建一个名为CountdownTime的项目,activity_main.xml代码如下:

代码语言:javascript复制
<?xml version="1.0" encoding="utf-8"? 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity" 

  <TextView
    android:id="@ id/countdownTimeTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="@string/maxTime"
    android:textSize="60sp" / 
</RelativeLayout 

MainActivity.class代码如下:

代码语言:javascript复制
public class MainActivity extends AppCompatActivity {

  /**
   * 倒计时标记
   */
  public static final int COUNTDOWN_TIME_CODE = 99999;
  /**
   * 倒计时间隔
   */
  public static final int DELAY_MILLIS = 1000;
  /**
   * 倒计时最大值
   */
  public static final int MAX_COUNT = 10;
  /**
   * 文本控件
   */
  private TextView countdownTimeTextView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //初始化文本控件
    countdownTimeTextView = findViewById(R.id.countdownTimeTextView);
    //创建一个handler
    CountdownTimeHandler handler = new CountdownTimeHandler(this);
    //新建一个message
    Message message = Message.obtain();
    message.what = COUNTDOWN_TIME_CODE;
    message.arg1 = MAX_COUNT;
    //第一次发送message
    handler.sendMessageDelayed(message, DELAY_MILLIS);
  }

  public static class CountdownTimeHandler extends Handler {
    /**
     * 倒计时最小值
     */
    public static final int MIN_COUNT = 0;
    //创建MainActivity弱引用
    final WeakReference<MainActivity  mWeakReference;

    public CountdownTimeHandler(MainActivity activity) {
      this.mWeakReference = new WeakReference< (activity);
    }

    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
      //获取对MainActivity的弱引用
      MainActivity activity = mWeakReference.get();
      switch (msg.what) {
        case COUNTDOWN_TIME_CODE:
          int value = msg.arg1;
          activity.countdownTimeTextView.setText(String.valueOf(value--));
          //循环发送消息的控制
          if (value  = MIN_COUNT) {
            Message message = Message.obtain();
            message.what = COUNTDOWN_TIME_CODE;
            message.arg1 = value;
            sendMessageDelayed(message, DELAY_MILLIS);
          }
          break;
      }
    }
  }
}

3、快捷键总结

Ctrl Alt F:改变变量的域 Ctrl Alt T:surrounded with快捷键 Ctrl P:查看方法的参数

以上就是本文的全部内容,希望对大家的学习有所帮助。

0 人点赞