简体   繁体   中英

display time played for sudoku in android

I need to display the time ticking a sudoku game has been played, the time played must be displayed on the screen. This means i should be able to record the time from when the sudoku activity has been started till the game fineshes. can anyone help me how to do this in android.

I use this code every time I need to display time elapsed in a game. First you have this TextView for showing your time, defined in your xml, nothing special about it. The code in your game activity is:

    TextView time;

    long countUp;

    public static Chronometer.OnChronometerTickListener chronListener = new Chronometer.OnChronometerTickListener() {
        String msg;

        @Override
        public void onChronometerTick(Chronometer ch){
            countUp = (SystemClock.elapsedRealtime() - ch.getBase()) / 1000;
            msg = showTime(countUp);
            time.setText("Time: " + msg);
        }           
    };


//a function formatting your time in human readable format, e.g. 05:06
    public static String showTime(long countUp){
        String asText;
        if((countUp % 60) < 10){
            if((countUp / 60) < 10){
                asText = "0" + (countUp / 60) + ":0" + (countUp % 60); 
            } else {
                asText = (countUp / 60) + ":0" + (countUp % 60); 
            }
        } else {
            if ((countUp / 60) < 10){
                asText = "0" + (countUp / 60) + ":" + (countUp % 60);
            } else {
                asText = (countUp / 60) + ":" + (countUp % 60); 
            }
        }
        return asText;
    }

It works like a charm.

I would suggest looking into a Handler and the postDelayed method. This is a great option for second intervals, but it tends to choke up at like 25 milliseconds in my very brief experience. http://developer.android.com/reference/android/os/Handler.html#postDelayed%28java.lang.Runnable,%20long%29

Then make a runnable that changes a variable of time, and updates a TextView in your app with the new time. It will have to be formatted as well. http://developer.android.com/reference/java/lang/Runnable.html

This should help you grasp the idea and has some example code: http://www.vogella.de/articles/AndroidPerformance/article.html

To implement it, you will need a way to determine if the user has won, and when they do, you need to remove the callbacks from the Handler, and then you will have the total time in your variable (use a long) holding the number of milliseconds they have played.

Feel free to comment with questions and hopefully I can help ya out. It took me a while to figure out how to do these things so I'm happy to point you in the right direction if you get stuck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM