如何在android中显示每秒动态变化的当前时间

Nav*_*uel 13 android

我需要在textview中显示当前时间,并且动态时间每秒动态变化(如数字时钟)在android中..我用谷歌搜索但我没有得到帮助.如果有人有这个想法,请帮助我谢谢提前.

Bha*_*vin 25

这是代码..

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    Thread myThread = null;

    Runnable myRunnableThread = new CountDownRunner();
    myThread= new Thread(myRunnableThread);   
    myThread.start();

}

public void doWork() {
    runOnUiThread(new Runnable() {
        public void run() {
            try{
                TextView txtCurrentTime= (TextView)findViewById(R.id.myText);
                    Date dt = new Date();
                    int hours = dt.getHours();
                    int minutes = dt.getMinutes();
                    int seconds = dt.getSeconds();
                    String curTime = hours + ":" + minutes + ":" + seconds;
                    txtCurrentTime.setText(curTime);
            }catch (Exception e) {}
        }
    });
}


class CountDownRunner implements Runnable{
    // @Override
    public void run() {
            while(!Thread.currentThread().isInterrupted()){
                try {
                doWork();
                    Thread.sleep(1000); // Pause of 1 Second
                } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                }catch(Exception e){
                }
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @user:每当你想要停止Thread时使用thread.interrupt().如果你想在活动停止时杀死线程,那么你可以将它添加到Activity的重写方法stop或destroy. (2认同)

Nik*_*esh 16

使用TextClock.这个wil会在没有单独代码的情况下动态变化.

        <TextClock
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/textClock"
            android:layout_weight="0.11"
            android:textStyle="bold"
            android:textSize="22sp"
            android:format24hours="hh:mm:ss a  EEE MMM d"/>

    TextClock textClock = (TextClock) findViewById(R.id.textClock);
    textClock.setFormat12Hour(null);
    //textClock.setFormat24Hour("dd/MM/yyyy hh:mm:ss a");
    textClock.setFormat24Hour("hh:mm:ss a  EEE MMM d");
Run Code Online (Sandbox Code Playgroud)


Ayy*_*pan 12

使用CountDownTimer类,为CountDownTimer生命传递一个巨大的值(这里我给了1000000000).

示例代码::

CountDownTimer newtimer = new CountDownTimer(1000000000, 1000) { 

            public void onTick(long millisUntilFinished) {
                Calendar c = Calendar.getInstance();
                textView.setText(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND));
            }
            public void onFinish() {

            }
        };
        newtimer.start();
Run Code Online (Sandbox Code Playgroud)

关闭活动时,请调用以下函数

newtimer.cancel();
Run Code Online (Sandbox Code Playgroud)


Luc*_*fer 6

你可以使用ThreadClass with sleep(1000); 或者你可以使用TimerTaskClass.


Gau*_*wal 5

Chronometer在Android中使用类。