我有Button
,按下后,应该开始倒计时,并在按钮上显示倒数。
我该怎么办?
答案 0 :(得分:3)
试试这个
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();
}
}
答案 1 :(得分:2)
以下代码将非常简单地实现您的要求。现在这非常简单。您需要实施onFinish()
并可能实施onTick()
一点。但这是能够轻松完成您想要的代码的最少代码。
您想要做的是使用随android api提供的CountDownTimer
。
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();
}
});