Handler实现倒计时
程序员文章站
2022-07-14 17:05:18
...
通过Handler实现一个倒计时的功能
具体代码如下:
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final int COUNTDOWN_TIME_CODE = 10001;
public static final int DELAY_MILLIS = 1000;
public static final int MAX_COUNT = 10;
public static final int MIN_COUNT = 0;
private TextView mCountDownText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCountDownText = (TextView) findViewById(R.id.coun_down_num);
CountingHandler handler = new CountingHandler(this);
//通过CountingHandler发送Message
Message message = Message.obtain();
message.what = COUNTDOWN_TIME_CODE;
message.arg1 = MAX_COUNT;
//设置延迟发送时间1s
handler.sendMessageDelayed(message, DELAY_MILLIS);
}
/**
* 实现CountingHandler类,利用弱引用避免内存泄漏
*/
public static class CountingHandler extends Handler{
final WeakReference<MainActivity> mWeakReference;
//构造方法传入MainActivity
public CountingHandler(MainActivity activity) {
mWeakReference = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//通过activity得到TextView控件
MainActivity activity = mWeakReference.get();
switch (msg.what){
case COUNTDOWN_TIME_CODE:
int value = msg.arg1;
//更新UI
activity.mCountDownText.setText(String.valueOf(--value));
if (value > MIN_COUNT) {
//新建message将value作为参数
Message message = Message.obtain();
message.what = COUNTDOWN_TIME_CODE;
message.arg1 = value;
sendMessageDelayed(message, DELAY_MILLIS);
}
break;
}
}
}
}
运行结果便是UI的TextView 每隔1s从10减到0。是通过sendMessageDelay()方法实现的。
上一篇: Handler倒计时
下一篇: 线程 handler looper