CountDownTimer Class:
developer URL:
http://developer.android.com/reference/android/os/CountDownTimer.html
我实现的效果图:
代码目录文件:
主要代码讲解:
1.三个button:add,sub,start;
2.两个显示textview:count,show;
具体使用到方法讲解:
init();
click();
setBrewCount(0);
setBrewTime(3);
startTime();
stopTime();
.
详细代码如下:
package com.example.countdowntimedemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
private Button add,sub,start;
private TextView count,show;
private CountDownTimer countDownTimer;
private int countTime=0;
private int brewTime=3;
private boolean state=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
add=(Button)findViewById(R.id.add);
sub=(Button)findViewById(R.id.sub);
start=(Button)findViewById(R.id.start);
count=(TextView)findViewById(R.id.count);
show=(TextView)findViewById(R.id.show);
click();
}
private void click() {
add.setOnClickListener(this);
sub.setOnClickListener(this);
start.setOnClickListener(this);
setBrewCount(0);
setBrewTime(3);
}
private void setBrewTime(int i) {
if(state)
return;
brewTime=i;
if(brewTime<1){
brewTime=1;
}
show.setText(String.valueOf(brewTime)+"m");
}
private void setBrewCount(int i) {
countTime=i;
count.setText(String.valueOf(countTime));
}
private void startTime(){
countDownTimer=new CountDownTimer(brewTime*60*1000,1000) {
@Override
public void onTick(long millisUntilFinished) {
show.setText(String.valueOf(millisUntilFinished/1000)+"s");
}
@Override
public void onFinish() {
state=false;
setBrewCount(countTime+1);
show.setText("break up");
start.setText("start");
}
};
countDownTimer.start();
start.setText("stop");
state=true;
}
private void stopTime(){
if(countDownTimer!=null){
countDownTimer.cancel();
}
state=false;
start.setText("start");
}
@Override
public void onClick(View v) {
if(v==add){
setBrewTime(brewTime+1);
}else if(v==sub){
setBrewTime(brewTime-1);
}else if(v==start){
if(state){
stopTime();
}else{
startTime();
}
}
}
}
demo网盘地址:http://pan.baidu.com/s/1lXee6(无效请私信我:fengjianweixx@gmail.com)