国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

android利用handler實現倒計時功能

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

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

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發出去 Message message = Message.obtain(); message.what = COUNT_DOWN_CODE; message.arg1 = value; sendMessageDelayed(message, DELAY_MILLIS); } break; } } }}

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

標簽: Android
相關文章:
主站蜘蛛池模板: 桦甸市| 新和县| 延安市| 合川市| 太原市| 烟台市| 深圳市| 金乡县| 车致| 商水县| 绥德县| 新晃| 黎城县| 于都县| 鹤峰县| 青冈县| 尉氏县| 洛扎县| 民乐县| 新竹市| 塔河县| 石林| 西林县| 长海县| 会宁县| 怀集县| 朝阳区| 白玉县| 虹口区| 汝城县| 墨玉县| 观塘区| 平潭县| 高要市| 钟山县| 肥东县| 米林县| 合山市| 舞阳县| 芮城县| 鹤庆县|