本文实例为大家分享了android实现倒计时功能的具体代码,供大家参考,具体内容如下
【思路】:通过 timer 执行周期延时的任务,handler 中将计时信息更新,并在计时结束时结束 timer 的周期任务。
- 在布局文件中添加一个TextView和Button控件,并在onCreate方法中获得到TextView和Button的id;
xml布局代码:
<Button android:id="@+id/button_start_timer" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_gravity="center_vertical" android:gravity="center" android:text="开始" android:textSize="12sp" /> <TextView android:id="@+id/textViewTime24" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="2" android:gravity="center" android:text="24" android:textColor="#33ff00" android:textSize="60sp" />
java代码
package com.example.wlf.gamerecorder.gameon; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.os.Handler; import com.example.wlf.gamerecorder.R; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class SimpleGameonActivity extends AppCompatActivity { private final static int COUNT = 1; private final static int TOTAL_TIME_24 = 24; private TextView textViewTime24; Timer timer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple_gameon); textViewTime24=(TextView)findViewById(R.id.textViewTime24);//24秒倒计时 final Button button_start_timer = (Button)findViewById(R.id.button_start_timer); button_start_timer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String str = button_start_timer.getText().toString();//获取按钮字符串 if(str.equals("开始")){ //切换按钮文字 button_start_timer.setText("暂停"); initView(); } else{ button_start_timer.setText("开始"); timer.cancel();//终止线程 } } }); } public void initView(){ //countDown = (TextView) findViewById(R.id.textViewTime24); timer = new Timer(); /** * 每一秒发送一次消息给handler更新UI * schedule(TimerTask task,long delay,long period) */ timer.schedule(new TimerTask() { @Override public void run() { handler.sendEmptyMessage(COUNT); } },1000); } private Handler handler = new Handler(){ int num = TOTAL_TIME_24; public void handleMessage(android.os.Message msg) { switch (msg.what) { case COUNT: textViewTime24.setText(String.valueOf(num)); if(num == 0) timer.cancel();//0秒结束 num--; break; default: break; } }; }; }