这篇文章主要为大家详细介绍了android利用handler实现倒计时功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了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:id="@+id/text"
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利用handler实现倒计时功能


基础教程推荐
猜你喜欢
- 解决Android Studio突然不显示logcat日志的问题 2023-02-04
- IOS 播放系统提示音使用总结(AudioToolbox) 2023-03-01
- Android开发使用RecyclerView添加点击事件实例详解 2023-06-15
- Android中的webview监听每次URL变化实例 2023-01-23
- android studio按钮监听的5种方法实例详解 2023-01-12
- Flutter手势密码的实现示例(附demo) 2023-04-11
- Android多返回栈技术 2023-04-15
- Flutter绘图组件之CustomPaint使用详解 2023-05-12
- iOS开发教程之XLForm的基本使用方法 2023-05-01
- IOS应用内跳转系统设置相关界面的方法 2022-11-20