十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
本篇文章給大家分享的是有關(guān)怎么在Android中利用Handler實(shí)現(xiàn)一個倒計(jì)時功能,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
專注于為中小企業(yè)提供網(wǎng)站設(shè)計(jì)制作、做網(wǎng)站服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)湞江免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了成百上千企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
代碼實(shí)現(xiàn)
新建一個名為CountdownTime的項(xiàng)目,activity_main.xml代碼如下:
MainActivity.class代碼如下:
public class MainActivity extends AppCompatActivity { /** * 倒計(jì)時標(biāo)記 */ public static final int COUNTDOWN_TIME_CODE = 99999; /** * 倒計(jì)時間隔 */ public static final int DELAY_MILLIS = 1000; /** * 倒計(jì)時最大值 */ 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); //創(chuàng)建一個handler CountdownTimeHandler handler = new CountdownTimeHandler(this); //新建一個message Message message = Message.obtain(); message.what = COUNTDOWN_TIME_CODE; message.arg1 = MAX_COUNT; //第一次發(fā)送message handler.sendMessageDelayed(message, DELAY_MILLIS); } public static class CountdownTimeHandler extends Handler { /** * 倒計(jì)時最小值 */ public static final int MIN_COUNT = 0; //創(chuàng)建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--)); //循環(huán)發(fā)送消息的控制 if (value >= MIN_COUNT) { Message message = Message.obtain(); message.what = COUNTDOWN_TIME_CODE; message.arg1 = value; sendMessageDelayed(message, DELAY_MILLIS); } break; } } } }
以上就是怎么在Android中利用Handler實(shí)現(xiàn)一個倒計(jì)時功能,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。