经过一段时间完成一项活动

2023-09-12 02:28:12 作者:社会社会,射射就会了

我想开发一款游戏像匹配的小pictures.My问题是,我想经过一段时间。对于实例1的水平,我们有10秒钟时间来匹配图片来完成比赛。我想显示剩余时间also.I应该心存感激的任何帮助。

I am trying to develop a game like matching small pictures.My problem is that i want to finish the game after a time period.For instance in level 1 we have 10 seconds to match picture.I want to display remaining time also.I will be thankful for any help.

推荐答案

既然你也想显示倒计时,我会建议的 CountDownTimer 。这样做的方法在每一个滴答,它可以是你在构造函数中设置的时间间隔采取行动。而且它是在 UI线程运行方式,所以你可以很容易地更新的TextView 等等...

Since you also want to show the countdown, I would recommend a CountDownTimer. This has methods to take action at each "tick" which can be an interval you set in the constructor. And it's methods run on the UI Thread so you can easily update a TextView, etc...

在它的 onFinish()方法,你可以调用完成()活动或做任何其他适当的行动。

In it's onFinish() method you can call finish() for your Activity or do any other appropriate action.

See这个答案的例子

修改更明显的例子

在这里,我有一个内部类其中扩展CountDownTimer

Here I have an inner-class which extends CountDownTimer

@Override
public void onCreate(Bundle savedInstanceState) {
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.some_xml);      
    // initialize Views, Animation, etc...

    // Initialize the CountDownClass
    timer = new MyCountDown(11000, 1000);
}

// inner class
private class MyCountDown extends CountDownTimer
{
    public MyCountDown(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        frameAnimation.start();
        start();            
    }

    @Override
    public void onFinish() {
        secs = 10;
       // I have an Intent you might not need one
        startActivity(intent);
        YourActivity.this.finish(); 
    }

    @Override
    public void onTick(long duration) {
        cd.setText(String.valueOf(secs));
        secs = secs - 1;            
    }   
}
相关推荐