我有一个Button
,按下后,应该开始倒计时,并在按钮上显示倒计时。
我该如何进行?
以下代码将非常简单地实现您的要求。现在这非常非常简单。您将需要实施onFinish()
并可能实施onTick()
更多。但这是轻松完成您想要的最少的代码。
您想要做的是使用CountDownTimer
android api 提供的。
private long countDown = 3000;
private long interval = 1000;
private CountDownTimer countDownTimer;
this.countDownTimer = new CountDownTimer(this.countDown, this.interval) {
@Override
public void onTick(long millisUntilFinished) {
colorButton.setText(Long.toString(millisUntilFinished/1000));
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
}
};
this.colorButton.setText(Long.toString(this.countDown/1000));
this.colorButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
countDownTimer.start();
}
});
试试这个
public class CountDown extends Activity implements OnClickListener {
Button btn;
int i=0, second = 3;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener( this );
}
@Override
public void onClick(View v) {
new Thread( new Runnable() {
public void run() {
while( i != second ) {
try {
handle.sendMessage( handle.obtainMessage());
Thread.sleep(1000);
} catch( Throwable t) {
}
}
}
Handler handle = new Handler() {
public void handleMessage( Message msg) {
btn.setText( ""+ second );
second--;
}
};
}).start();
}
}