java 如何在 Android 的 TextView 中显示计时器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/41499362/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display a timer in a TextView in Android?
提问by Larry Jing
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.
做一个计时器。所以文本应该是一个计时器,像 0:30 然后 0:29 ... 持续 30 秒。一旦计时器是 0:00,我就可以调用另一个方法;我可以打印出“再试一次”并重新启动计时器。
回答by
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);
}
回答by W4R10CK
Try code:
尝试代码:
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
    public int seconds = 60;
    public int minutes = 10;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Declare the timer
        Timer t = new Timer();
        //Set the schedule function and rate
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView tv = (TextView) findViewById(R.id.main_timer_text);
                        tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
                        seconds -= 1;
                        if(seconds == 0)
                        {
                            tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
                            seconds=60;
                            minutes=minutes-1;
                        }
                    }
                });
            }
        }, 0, 1000);
    }
}
回答by Yogesh Borhade
XML File
XML文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/mtextTimer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/buttonSend"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start" />
</LinearLayout>
Activity
活动
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView textTimer;
    private Button StartTimer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Initializing the views
        textTimer = (TextView) findViewById(R.id.mtextTimer);
        StartTimer = (Button) findViewById(R.id.buttonSend);
        StartTimer.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        long maxTimeInMilliseconds = 30000;// in your case
        startTimer(maxTimeInMilliseconds, 1000);
    }
    public void startTimer(final long finish, long tick) {
        CountDownTimer t;
        t = new CountDownTimer(finish, tick) {
            public void onTick(long millisUntilFinished) {
                long remainedSecs = millisUntilFinished / 1000;
                textTimer.setText("" + (remainedSecs / 60) + ":" + (remainedSecs % 60));// manage it accordign to you
            }
            public void onFinish() {
                textTimer.setText("00:00:00");
                Toast.makeText(MainActivity.this, "Finish", Toast.LENGTH_SHORT).show();
                cancel();
            }
        }.start();
    }
}
回答by Rajshah
public void settimer() {
    new CountDownTimer(30000, 1000) {
        public void onTick(long millisUntilFinished) {
            long remainedSecs = millisUntilFinished / 1000;
            forgotpasswordBinding.txtotptime.setText("" + (remainedSecs / 60) + ":" + (remainedSecs % 60));
        }
        public void onFinish() {
            forgotpasswordBinding.txtotptime.setText("Resend");
            forgotpasswordBinding.txtotptime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
            settimer();
                }
            });
        }
    }.start();
}
回答by Steve Hame
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Timer t = new Timer();    //declare the timer
    t.scheduleAtFixedRate(new TimerTask() { //Set the schedule function and rate
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    TextView mRefreshTime = (TextView) findViewById(R.id.screenStatusTvTime);
                    mRefreshTime.setText(String.format("%dh%02d'%02d\"", minutes/60, minutes%60, seconds));
                    if (++seconds == 60) {
                        seconds = 0;
                        minutes++;
                    }
                }
            });
        }
    }, 0L, 1000L);
回答by Pramesh Bhalala
 long MillisecondTime, TimeBuff, UpdateTime = 0L;
 int Seconds, Minutes, MilliSeconds;
 TextView textViewTimer = findViewById(R.id.timerTextView);
 public void startTimer() {
    new CountDownTimer(180000, 1000) {
        public void onTick(long millisUntilFinished) {
            MillisecondTime = millisUntilFinished;
            UpdateTime = TimeBuff + MillisecondTime;
            Seconds = (int) (UpdateTime / 1000);
            Minutes = Seconds / 60;
            Seconds = Seconds % 60;
            MilliSeconds = (int) (UpdateTime % 1000);
            textViewTimer.setText("0" + Minutes + ":"
                    + String.format("%02d", Seconds) + ":"
                    + String.format("",MilliSeconds));
        }
        public void onFinish() {
             textViewTimer.setText("Done!");
        }
    }.start();
}
Call startTimer()method and this will set timerto textViewfor e.g. start time 02:59:00
呼叫startTimer()方法,这将设置timer到textView了如启动时间2点59分00秒
回答by Benni sachin
timer will set for 3min like "2:59"
    private int time=60,n=2; 
        textTimer=findViewById(R.id.timer);
        // textview 
                    new CountDownTimer(180000, 1000) {
                        public void onTick(long millisUntilFinished)
                        {
                            if(time==0)
                            {
                                n--;
                                time=60;
                            }
                            textTimer.setText( n +":" + checkdigit(time));
                            time--;
                        }
                        public void onFinish() {
                        }
                    }.start();
     public String checkdigit(int number)
        {
            return number <= 9 ? "0" + number : String.valueOf(number);
        }

