重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
本篇文章給大家分享的是有關怎么在Android中利用Handler實現一個倒計時功能,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
專注于為中小企業提供網站設計制作、做網站服務,電腦端+手機端+微信端的三站合一,更高效的管理,為中小企業湞江免費做網站提供優質的服務。我們立足成都,凝聚了一批互聯網行業人才,有力地推動了成百上千企業的穩健成長,幫助中小企業通過網站建設實現規模擴充和轉變。
代碼實現
新建一個名為CountdownTime的項目,activity_main.xml代碼如下:
MainActivity.class代碼如下:
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 WeakReferencemWeakReference; 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; } } } }
以上就是怎么在Android中利用Handler實現一個倒計時功能,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注創新互聯行業資訊頻道。