Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 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 Reply

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...