简体   繁体   English

Java程序中的计时器,倒计时

[英]Timer in Java program, countdown

I want to implement a java countdown timer for my Android program but I don't know how should I do it. 我想为我的Android程序实现Java倒数计时器,但是我不知道该怎么做。 It should count the time from let's say 60 to 0 and at the end the program should end but the user needs to see how much time is left, so the timer should be visible all time. 它应该计算从60到0的时间,最后应该结束程序,但是用户需要查看还剩多少时间,因此计时器应该一直可见。 I managed to implement a "timer" for how long the game is accepting input but I don't understand how should I make a count down system. 我设法为游戏接受输入的时间实现了一个“计时器”,但是我不知道我应该如何制作一个倒计时系统。 Here is my source file for the program that I made. 这是我制作的程序的源文件。 Hope you guys can help me thanks in advance, 希望你们能提前帮助我,

  package com.example.mathcalcplus;

import java.util.Random;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class PlayGame extends Activity implements OnClickListener {
    ImageView image;
    TextView question, answer, score, timeLeft;
    int difLevel, operator1, operator2, finalAnswer=0, operation, scoreCount = 0, userAnswer=0;
    final private int add = 0, sub = 1, div = 3, mul = 2;
    String[] getOperation = { "+", "-", "*", "/"};
    Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnClear, btnEnter;
    Random rand;
    String getQuestion, userInput;
    long start;
    long end;
    boolean running = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.play_game);
        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        btn3 = (Button) findViewById(R.id.btn3);
        btn4 = (Button) findViewById(R.id.btn4);
        btn5 = (Button) findViewById(R.id.btn5);
        btn6 = (Button) findViewById(R.id.btn6);
        btn7 = (Button) findViewById(R.id.btn7);
        btn8 = (Button) findViewById(R.id.btn8);
        btn9 = (Button) findViewById(R.id.btn9);
        btn0 = (Button) findViewById(R.id.btn0);
        btnClear = (Button) findViewById(R.id.clear);
        btnEnter = (Button) findViewById(R.id.enter);   
        question = (TextView) findViewById(R.id.question);
        answer = (TextView) findViewById(R.id.answer);
        score = (TextView) findViewById(R.id.score);
        image = (ImageView) findViewById(R.id.response);
        timeLeft = (TextView) findViewById(R.id.timeLeft);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        btn5.setOnClickListener(this);
        btn6.setOnClickListener(this);
        btn7.setOnClickListener(this);
        btn8.setOnClickListener(this);
        btn9.setOnClickListener(this);
        btn0.setOnClickListener(this);
        btnClear.setOnClickListener(this);
        btnEnter.setOnClickListener(this);
        rand = new Random();
        Bundle extras = getIntent().getExtras();
        if(extras != null)
        {
            int passedLevel = extras.getInt("level", -1);
            if(passedLevel>=0) difLevel = passedLevel;
        }
        image.setVisibility(View.INVISIBLE);
        choseQuestion();
        start  = System.currentTimeMillis();
        end = start + 30*1000;
    }
public void run(){

}


    @Override
    public void onClick(View v) {
        switch (v.getId()){
        case R.id.enter:
            String getUserAnswer = answer.getText().toString();
            if (!getUserAnswer.endsWith("?")){

                userAnswer = Integer.parseInt(getUserAnswer.substring(1));

                if (userAnswer == finalAnswer){
                    scoreCount++;
                    score.setText("Score=" + " " + scoreCount);
                    image.setImageResource(R.drawable.tick);
                    image.setVisibility(View.VISIBLE);
                }
                else{
                    scoreCount = 0;
                    score.setText("Score=" + " " + scoreCount);
                    image.setImageResource(R.drawable.cross);
                    image.setVisibility(View.VISIBLE);
                }
                finalAnswer =0;
                choseQuestion();
                getUserAnswer = "";
                userAnswer = 0;
                break;

            }
            else{
                break;
            }



        case R.id.clear:
            answer.setText("=?");
            break;

        default:
            if (System.currentTimeMillis() < end){
            int enteredNum = Integer.parseInt(v.getTag().toString());
            if(answer.getText().toString().endsWith("?"))
                answer.setText("="+enteredNum);
            else
                answer.append(""+enteredNum);
            }
        }

    }
private void choseQuestion() {

        answer.setText("=?");
        operation = rand.nextInt(getOperation.length);
        operator1 = getNumbers();
        operator2 = getNumbers();
        if (operation == sub){
            while (operator2 > operator1){
                operator1 = getNumbers();
                operator2 = getNumbers();
            }
        }

        if (operation == div){
            while((double)operator1%(double)operator2 > 0 || (operator2 > operator1)){
                operator1 = getNumbers();
                operator2 = getNumbers();
            }
        }

        switch(operation){
        case add:
            finalAnswer = operator1 + operator2;
            break;

        case sub:
            finalAnswer = operator1 - operator2;
            break;

        case div:
            finalAnswer = operator1 / operator2;
            break;

        case mul:
            finalAnswer = operator1 * operator2;
            break;
        }
        question.setText(operator1 + getOperation[operation] +operator2);
        timeLeft.setText("Time :" + end);
    }

    private int getNumbers(){
        int n = rand.nextInt(100) + 1;`enter code here`
        return n;
    }

}
  1. Declare your CountDownTimer and you set the time range in miliseconds. 声明CountDownTimer然后将时间范围设置为毫秒。
  2. Call countDown method and your CountDownTimer is ready to go! 调用countDown方法,您的CountDownTimer准备就绪!

     private final static int time = 10000; private CountDownTimer timerCount; public void countDown(){ countDown = (TextView) findViewById(R.id.countdown); timerCount = new CountDownTimer(time, 1000) { public void onTick(long millisUntilFinished) { long tmp = millisUntilFinished / 1000; countDown.setText(tmp + ""); } public void onFinish() { // Do your stuff countDown.setText("0"); } }.start(); } 

And your .xml file 还有您的.xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/questionList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/menu"
android:orientation="vertical"
android:weightSum="4" >

<TextView
    android:id="@+id/title"
    android:layout_gravity="center"
    android:layout_width="wrap_content"
    android:textSize="14sp"
    android:layout_height="wrap_content"
/>

<TextView
    android:id="@+id/countdown"
    android:layout_gravity="right"
    android:layout_width="30dp"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="numberDecimal" >

    <requestFocus />
</TextView>

new CountDownTimer(60000, 1000) {

public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     //here you can have your logic to set text to edittext
}

public void onFinish() {
    mTextField.setText("done!");
}
}.start();

Here is the example . 这是例子

Refer to this link for countdowntimer. 有关倒数计时器,请参阅此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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