Android-两种方式实现倒计时

来源:互联网 发布:工会财务软件数据恢复 编辑:程序博客网 时间:2024/05/30 04:32

目标效果:

两个倒计时都是从20秒倒计时到0秒。


1.activity_main.xml页面:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <TextView        android:id="@+id/tvTime"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="100dp"        android:textSize="15sp"        android:gravity="center"        android:text="添加子线程倒计时00:20" />    <TextView        android:id="@+id/tvNoThreadTime"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="200dp"        android:textSize="15sp"        android:gravity="center"        android:text="未添加子线程倒计时00:20" /></RelativeLayout>


2.MainActivity.class页面:
package com.example.daojishi;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.app.Activity;import android.view.Menu;import android.widget.TextView;public class MainActivity extends Activity {private TextView tvTime, tvNoThreadTime;private int time = 20, noThreadTime = 20;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tvTime = (TextView) findViewById(R.id.tvTime);tvNoThreadTime = (TextView) findViewById(R.id.tvNoThreadTime);thread.start(); // 调用添加子线程的倒计时noThreadHandler.postDelayed(downTime, 1000); // 调用未添加子线程的倒计时}/* 使用线程进行倒计时 */// Handler用于子线程和主线程通信Handler handler = new Handler() {public void handleMessage(Message msg) {tvTime.setText("添加子线程倒计时00:" + msg.what);};};// 创建子线程倒计时Thread thread = new Thread(new Runnable() {@Overridepublic void run() {while (time > 0) {try {Thread.sleep(1000);time--;handler.sendEmptyMessage(time); // 向handler发送int型数据} catch (InterruptedException e) {e.printStackTrace();}}}});/* 未使用线程进行倒计时 */Handler noThreadHandler = new Handler();Runnable downTime = new Runnable() {@Overridepublic void run() {noThreadHandler.postDelayed(downTime, 1000); // 每隔一秒调用一次noThreadTime--;if (noThreadTime <= 0)noThreadHandler.removeCallbacks(downTime);   //停止调用tvNoThreadTime.setText("未添加子线程倒计时00:" + noThreadTime);}};}



0 0