久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

android利用handler實現(xiàn)倒計時功能

瀏覽:43日期:2022-09-21 15:34:24

本文實例為大家分享了android利用handler實現(xiàn)倒計時的具體代碼,供大家參考,具體內(nèi)容如下

xml

<?xml version='1.0' encoding='utf-8'?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android='http://schemas.android.com/apk/res/android' xmlns:app='http://schemas.android.com/apk/res-auto' xmlns:tools='http://schemas.android.com/tools' android:layout_width='match_parent' android:layout_height='match_parent' tools:context='.MainActivity'> <TextView android: android:layout_width='wrap_content' android:layout_height='wrap_content' android:text='Hello World!' app:layout_constraintBottom_toBottomOf='parent' app:layout_constraintLeft_toLeftOf='parent' app:layout_constraintRight_toRightOf='parent' app:layout_constraintTop_toTopOf='parent' /></androidx.constraintlayout.widget.ConstraintLayout>

java

package com.tcy.handlertest;import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.widget.TextView;import java.lang.ref.WeakReference;public class MainActivity extends AppCompatActivity { /** * 倒計時標記handler code */ public static final int COUNT_DOWN_CODE = 10001; /** * 倒計時最大值 */ public static final int MAX_COUNT = 10; /** * 倒計時間隔 */ public static final int DELAY_MILLIS = 1000; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); CountdownTimeHandler handler = new CountdownTimeHandler(this); Message message = Message.obtain(); message.what = COUNT_DOWN_CODE; message.arg1 = MAX_COUNT; handler.sendMessageDelayed(message, DELAY_MILLIS); } public static class CountdownTimeHandler extends Handler { //弱引用加在上下文上面 final WeakReference<MainActivity> weakReference; //這個方法要改一下,這樣就能直接傳進來上下文 public CountdownTimeHandler(MainActivity activity) { this.weakReference = new WeakReference<>(activity); } @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); //得到上下文 MainActivity activity = weakReference.get(); switch (msg.what) { case COUNT_DOWN_CODE: int value = msg.arg1; activity.textView.setText(String.valueOf(value--)); if (value >= 0) { //再把value發(fā)出去 Message message = Message.obtain(); message.what = COUNT_DOWN_CODE; message.arg1 = value; sendMessageDelayed(message, DELAY_MILLIS); } break; } } }}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標簽: Android
相關(guān)文章:
主站蜘蛛池模板: 新田县| 北海市| 祁连县| 阳山县| 西城区| 旌德县| 高州市| 文化| 广南县| 白河县| 报价| 叙永县| 闽清县| 循化| 如皋市| 廊坊市| 临潭县| 泸定县| 荆州市| 民勤县| 新野县| 甘谷县| 阳高县| 凤凰县| 洛南县| 涿鹿县| 宁德市| 习水县| 南投市| 博客| 康保县| 长沙市| 荣昌县| 马鞍山市| 莱西市| 浦县| 高淳县| 南京市| 泽普县| 岳阳市| 伊金霍洛旗|