如何在安卓中动态地每秒显示当前时间

14

我需要在Android应用程序中以文本视图的形式显示当前时间,并且时间每秒钟动态更改(就像数字时钟)。 我已经尝试过谷歌搜索,但没有得到帮助。如果有人知道如何实现,请给我提供帮助。 谢谢。


6个回答

26

这是代码...

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

我很想知道如何使用Fragments来实现这个。在这个问题上,我遇到了一个错误... runOnUiThread(new Runnable() { - princepiero
它的工作效果非常棒,但是当活动停止时我需要终止线程。如何做到这一点? - user
2
@user:每当您想要停止线程时,请使用thread.interrupt()。如果您希望在活动停止时终止线程,则可以将其添加到Activity的重写方法stop或destroy中。 - Bhavin

22

使用TextClock。这将动态更改,无需单独的代码。

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

1
谢谢你。在我找到这个之前,发现了很多糟糕的黑客技巧。 - Ben Kane
1
非常简单。谢谢。 - Nicoolasens

15

使用CountDownTimer类,将一个巨大的值(这里我给了1000000000)传递给CountDownTimer生命周期。

示例代码:

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();
在关闭Activity时,调用以下函数。
newtimer.cancel();

6

您可以使用 Thread 类并使用 sleep(1000) 方法,或者您可以使用 TimerTask 类。


5

2

为此,您应该尝试使用计时器,通过它,您可以实现您的目标,祝您好运。

Chronometer的示例代码在这里:

在main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />
<Chronometer
 android:id="@+id/chronometer"
 android:layout_gravity="center_horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
 />
<Button
 android:id="@+id/buttonstart"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Start"
 />
<Button
 android:id="@+id/buttonstop"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Stop"
 />
<Button
 android:id="@+id/buttonreset"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Reset"
 />
</LinearLayout>

在Java文件中

package com.exercise.AndroidChronometer;

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;

public class AndroidChronometer extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
       Button buttonStart = (Button)findViewById(R.id.buttonstart);
       Button buttonStop = (Button)findViewById(R.id.buttonstop);
       Button buttonReset = (Button)findViewById(R.id.buttonreset);

       buttonStart.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    myChronometer.start();
   }});

       buttonStop.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    myChronometer.stop();

   }});

       buttonReset.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    myChronometer.setBase(SystemClock.elapsedRealtime());

   }});


   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接