先看一下效果:
具体的实现方式:
package module.countdowntimer;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final long COUNTER_TIME = 10;
private Button mRetryButton;
private boolean mGameOver;
private boolean mGamePaused;
private long mTimeRemaining;
private CountDownTimer mCountDownTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRetryButton = ((Button) findViewById(R.id.retry_button));
mRetryButton.setVisibility(View.INVISIBLE);
mRetryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startGame();
}
});
startGame();
}
@Override
public void onResume() {
super.onResume();
if (!mGameOver && mGamePaused) {
resumeGame();
}
}
private void startGame() {
mRetryButton.setVisibility(View.INVISIBLE);
createTimer(COUNTER_TIME);
mGamePaused = false;
mGameOver = false;
}
private void resumeGame() {
createTimer(mTimeRemaining);
mGamePaused = false;
}
private void createTimer(long time) {
final TextView textView = ((TextView) findViewById(R.id.timer));
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
mCountDownTimer = new CountDownTimer(time * 1000, 50) {
@Override
public void onTick(long millisUnitFinished) {
mTimeRemaining = ((millisUnitFinished / 1000) + 1);
textView.setText("seconds remaining: " + mTimeRemaining);
}
@Override
public void onFinish() {
textView.setText("You Lose!");
mRetryButton.setVisibility(View.VISIBLE);
mGameOver = true;
}
};
mCountDownTimer.start();
}
}