java - 在 Android Studio 中设置倒计时器

标签 java android timer

我正在尝试创建一个在左上角有倒计时器的游戏。

我创建了一个 TextView 框并将其命名为“时间”,据我所知,计时器已正确设置,但它没有显示任何内容。

我的代码如下:

public class GameView extends SurfaceView implements SurfaceHolder.Callback {

/* Member (state) fields   */
private GameLoopThread gameLoopThread;
private Paint paint; //Reference a paint object 
/** The drawable to use as the background of the animation canvas */
private Bitmap mBackgroundImage;
// For creating the game Sprite
private Sprite sprite;
// For recording the number of hits
private int hitCount;

public GameView(Context context) {
    super(context);
    // Focus must be on GameView so that events can be handled.
    this.setFocusable(true);
    // For intercepting events on the surface.
    this.getHolder().addCallback(this);
    // Background image added
    mBackgroundImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.half_moon);

}
 /* Called immediately after the surface created */
public void surfaceCreated(SurfaceHolder holder) {
    // We can now safely setup the game start the game loop.
    ResetGame();//Set up a new game up - could be called by a 'play again option'
    mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, getWidth(), getHeight(), true);
    gameLoopThread = new GameLoopThread(this.getHolder(), this);
    gameLoopThread.running = true;
    gameLoopThread.start();
}

// For the countdown timer
private long startTime; // Timer to count down from
private final long interval = 1 * 1000; // 1 sec interval
private CountDownTimer countDownTimer; // Reference to the class
private boolean timerRunning = false;
private String displayTime; // To display the time on the screen
private TextView time = (TextView) findViewById(R.id.time);

// Countdown Timer - private class
private class MyCountDownTimer extends CountDownTimer {

    public MyCountDownTimer (long startTime, long interval) {
        super(startTime, interval);
    }
    public void onFinish() {
        displayTime = "Time is up!";
        timerRunning = false;
        countDownTimer.cancel();
    }
    public void onTick (long millisUntilFinished) {
        displayTime = " " + millisUntilFinished / 1000;

    }
}

//To initialise/reset game
private void ResetGame(){
    /* Set paint details */
    paint = new Paint();
    paint.setColor(Color.WHITE); 
    paint.setTextSize(20);
    sprite = new Sprite(this);
    hitCount = 0;
    // Set timer
    startTime = 10; // Start at 10s to count down
    // Create new object - convert startTime to milliseconds
    countDownTimer = new MyCountDownTimer(startTime*1000, interval);
    countDownTimer.start(); // Start the time running
    timerRunning = true;


}


//This class updates and manages the assets prior to drawing - called from the Thread
public void update(){

    sprite.update();

}
/**
 * To draw the game to the screen
 * This is called from Thread, so synchronisation can be done
 */
public void doDraw(Canvas canvas) {
    //Draw all the objects on the canvas
    canvas.drawBitmap(mBackgroundImage, 0, 0, null);
    canvas.drawText("The Game ",15,25, paint);
    sprite.draw(canvas);
}

//To be used if we need to find where screen was touched
public boolean onTouchEvent(MotionEvent event) {
        if (sprite.wasItTouched(event.getX(), event.getY())) {
            // This just renews the sprite for now
            sprite = new Sprite(this);
            hitCount++;
        }
    return true;
}

public void surfaceDestroyed(SurfaceHolder holder) {
    gameLoopThread.running = false;

    // Shut down the game loop thread cleanly.
    boolean retry = true;
    while(retry) {
        try {
            gameLoopThread.join();
            retry = false;
        } catch (InterruptedException e) {}
    }
}

public void getHitCount() {

}

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

}



}

一如既往,我们非常感谢任何帮助。

最佳答案

public class GameView extends SurfaceView implements SurfaceHolder.Callback {

/* Member (state) fields   */
private GameLoopThread gameLoopThread;
private Paint paint; //Reference a paint object 
/** The drawable to use as the background of the animation canvas */
private Bitmap mBackgroundImage;
// For creating the game Sprite
private Sprite sprite;
// For recording the number of hits
private int hitCount;
private TextView time;
Handler handler = new Handler();

public GameView(Context context) {
    super(context);
    // Focus must be on GameView so that events can be handled.
    this.setFocusable(true);
    // For intercepting events on the surface.
    this.getHolder().addCallback(this);
    // Background image added
    mBackgroundImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.half_moon);
    time = (TextView) context.findViewById(R.id.time);
    handler = new Handler();
}

 /* Called immediately after the surface created */
public void surfaceCreated(SurfaceHolder holder) {
    // We can now safely setup the game start the game loop.
    ResetGame();//Set up a new game up - could be called by a 'play again option'
    mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, getWidth(), getHeight(), true);
    gameLoopThread = new GameLoopThread(this.getHolder(), this);
    gameLoopThread.running = true;
    gameLoopThread.start();
}

// For the countdown timer
private long startTime; // Timer to count down from
private final long interval = 1 * 1000; // 1 sec interval
private CountDownTimer countDownTimer; // Reference to the class
private boolean timerRunning = false;
private String displayTime; // To display the time on the screen


// Countdown Timer - private class
private class MyCountDownTimer extends CountDownTimer {

    public MyCountDownTimer (long startTime, long interval) {
        super(startTime, interval);
    }
    public void onFinish() {
        displayTime = "Time is up!";
        timerRunning = false;
        countDownTimer.cancel();
    }
    public void onTick (long millisUntilFinished) {
        int dTime = (millisUntilFinished / 1000);
        displayTime = " " + dTime;
        Log.d("displayTime: ", displayTime);
        if(time != null){          
          handler.post(new Runnable(){
            time.setText(displayTime);
          });              
        }
    }
}

//To initialise/reset game
private void ResetGame(){
    /* Set paint details */
    paint = new Paint();
    paint.setColor(Color.WHITE); 
    paint.setTextSize(20);
    sprite = new Sprite(this);
    hitCount = 0;
    // Set timer
    startTime = 10; // Start at 10s to count down
    // Create new object - convert startTime to milliseconds
    countDownTimer = new MyCountDownTimer(startTime*1000, interval);
    countDownTimer.start(); // Start the time running
    timerRunning = true;


}


//This class updates and manages the assets prior to drawing - called from the Thread
public void update(){

    sprite.update();

}
/**
 * To draw the game to the screen
 * This is called from Thread, so synchronisation can be done
 */
public void doDraw(Canvas canvas) {
    //Draw all the objects on the canvas
    canvas.drawBitmap(mBackgroundImage, 0, 0, null);
    canvas.drawText("The Game ",15,25, paint);
    sprite.draw(canvas);
}

//To be used if we need to find where screen was touched
public boolean onTouchEvent(MotionEvent event) {
        if (sprite.wasItTouched(event.getX(), event.getY())) {
            // This just renews the sprite for now
            sprite = new Sprite(this);
            hitCount++;
        }
    return true;
}

public void surfaceDestroyed(SurfaceHolder holder) {
    gameLoopThread.running = false;

    // Shut down the game loop thread cleanly.
    boolean retry = true;
    while(retry) {
        try {
            gameLoopThread.join();
            retry = false;
        } catch (InterruptedException e) {}
    }
}

public void getHitCount() {

}

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

}



}

关于java - 在 Android Studio 中设置倒计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42949331/

相关文章:

android - 当我单击另一个自定义 ListView 项时填充自定义 ListView

android - 如何在 Android EditText 中进行提示换行?

android - 在所有事件中放置提醒 android 日历

go - 关于时间的准确性.Timer

c# - 继承System.Timers.Timer时替换System.Timers.Timer.Elapsed事件

java - 类的对象作为类内的实例变量

java - 创建行和列

java - 无法从字符串转换为(应该是另一个字符串)

c++ - 如何在C++中使用定时器强制在给定时间内输入?

java - 我正在尝试从 Excel 工作表获取数据并将测试数据传递到登录名和密码字段中,但出现以下错误