Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

java - How to display a timer in a TextView in Android?

I want to set this textview:

<TextView
    android:id="@+id/timer"
    android:layout_width="100dp"
    android:layout_height="30dp"
    android:layout_above="@+id/directions"/>

To be a timer. So the text should be a timer going like 0:30 then 0:29 ... for 30 seconds. Once timer is 0:00, I can call another method; I can print out "try again" and restart timer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
int time=30;
TextView textTimer = (TextView)findViewById(R.id.timer);

new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {  
        textTimer.setText("0:"+checkDigit(time));
        time--;         
    }

    public void onFinish() {
        textTimer.setText("try again");
    }

}.start();



public String checkDigit(int number) {
    return number <= 9 ? "0" + number : String.valueOf(number);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...