我想为我的游戏添加一个计时器。我不完全确定如何做到这一点。我是android编码的新手。游戏与在一定时间内点击按钮有关。我让计数器工作我喜欢它,但是在添加倒数计时器时遇到了问题。
计时器应运行30秒,我希望显示秒数:毫秒,我也不确定。
我曾尝试过创建过一次,并添加了计数器和计时器,但我遇到的另一个问题是我在游戏画面上只有1个按钮需要启动计时器并计数,但是我最后一次这样做,每次我点击按钮,计时器将重新开始,并在上一次点击的同时继续计数。
任何人都可以帮我吗?如果可能的话,我也会喜欢这样简短的解释。
到目前为止我的代码:
public class GameActivity extends Activity
{
int score = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
/** This is the score calculator */
final ImageView startgametitleImage = (ImageView)findViewById(R.id.startgameImage);
final TextView currentScore = (TextView)findViewById(R.id.gameScore);
currentScore.setText("");
final Button startButton = (Button)findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
score++;
currentScore.setText("Score: " + score);
currentScore.setTextSize(40);
currentScore.setTextColor(Color.WHITE);
startgametitleImage.setImageDrawable(null);
}
});
}
}
答案 0 :(得分:0)
试试这段代码:
private TextView txtCount, textViewTimer;
private Button btnCount, btnRestart;
int count = 0;
boolean[] timerProcessing = { false };
boolean[] timerStarts = { false };
private MyCount timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtCount = (TextView) findViewById(R.id.textView1);
txtCount.setText(String.valueOf(count));
btnCount = (Button) findViewById(R.id.button1);
btnRestart = (Button) findViewById(R.id.button2);
textViewTimer = (TextView) findViewById(R.id.textView2);
timer = new MyCount(10000, 1);
btnCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// start timer once when button first click
if (!timerStarts[0]) {
timer.start();
timerStarts[0] = true;
timerProcessing[0] = true;
}
if (timerProcessing[0]) {
count++;
txtCount.setText(String.valueOf(count));
}
}
});
btnRestart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
timerProcessing[0] = true;
count = 0;
txtCount.setText(String.valueOf(count));
timer.cancel();
timer.start();
}
});
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
textViewTimer.setText("0:000");
timerProcessing[0] = false;
}
@Override
public void onTick(long millisUntilFinished) {
textViewTimer.setText("" + millisUntilFinished / 1000 + ":"
+ millisUntilFinished % 1000);
}
}
这里你的计数器varibale被一个内部类替换,所以你不需要每次都创建计数器变量。如果要重新启动计数器,只需创建一次计数器变量并调用它的start方法。
答案 1 :(得分:0)