在 Android 中显示当前时间并更新它?

Showing current time in Android and updating it?

我想显示当前时间并保持更新,格式示例为:09:41 Hour:Minute。 TextView 可以做吗?我尝试了一些方法,但我没有得到我真正想要的。

Android 对此已有看法。

http://developer.android.com/reference/android/widget/TextClock.html

你可以直接在XML中这样使用

<TextClock
    android:id="@+id/textClock"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />

它是最小值 api 17,因此如果您需要低于该数值,只需查看

http://developer.android.com/reference/android/widget/DigitalClock.html

最坏的情况是您可以子类化 textview 并从 textclock 源代码中窃取代码。它应该相当简单

像这样应该可以解决问题

final Handler someHandler = new Handler(getMainLooper());   
        someHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tvClock.setText(new SimpleDateFormat("HH:mm", Locale.US).format(new Date()));
                someHandler.postDelayed(this, 1000);
            }
        }, 10);

您应该保留对处理程序和可运行对象的引用,以便在 Activity 暂停时取消此操作,并在恢复时恢复。确保删除所有回调到处理程序并将其设置为 onDestroy

中的 null
  boolean run=true; //set it to false if you want to stop the timer
  Handler mHandler = new Handler();


 public void timer() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (run) {
                    try {
                        Thread.sleep(20000);
                        mHandler.post(new Runnable() {

                            @Override
                            public void run() {
                                Calendar c = Calendar.getInstance();
                                int min = c.get(Calendar.MINUTE);
                                int hour=c.get(Calendar.HOUR);
                                TextView.setText(String.valueOf(hour)+":"+String.valueOf(min));
                            }
                        });
                    } catch (Exception e) {
                    }
                }
            }
        }).start();}

在 onCreate 中这样调用它

  timer();

要获取时间和日期,您可以使用日历 class

Calendar cal = Calendar.getInstance();
String time = ""+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE);

为什么不用Java的Timer和TimerTask?它们非常简单、可靠且易于理解。

这是一个例子:

public class ClockCounter extends TimerTask{

    private long time = System.currentTimeMillis();

    @Override
    public void run(){
        time += 1000; //add 1 second to the time
        //convert ms time to viewable time and set MainActivity.text (textview) text to this.
    }

    public long getTime(){ return time; }
}

public class MainActiviy extends Activity{

    public static TextView text;
    private Timer timer;

    @Override
    public void onCreate(){
        //default code
        //set text view according to id
        timer = new Timer();
        timer.schedule(new ClockCounter(), 0, 1000); //schedule clock counter to repeat every 1 seconds (1000 ms)
    }
}

我知道那里有一些说明,但是任何 android 在 Java 方面具有合理经验的开发人员都应该能够弄清楚如何做这些事情。

希望对您有所帮助!

编辑 要将日期格式化为可查看的字符串,您可以使用以下代码(也仅使用 Java 提供的 API)

Date date = new Date();
DateFormat formatter = new SimpleDateFormat("HH:mm"); //Hourse:Minutes
String dateFormatted = formatter.format(date); //string representation

对于直接使用 TextClock

需要自定义日期和时间的人
  • 时间格式:android:format12Hour="hh:mm:ss a"
  • 日期格式: android:format24Hour="MMM dd, yyyy"
<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layoutContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bg_screenlock"
        app:layout_constraintStart_toStartOf="parent">

        <TextClock
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="60dp"
            android:gravity="center"
            android:textColor="@color/_white"
            android:textSize="70sp"
            android:format12Hour="hh:mm:ss a"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextClock
            android:id="@+id/textDateTime"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textColor="@color/_white"
            android:textSize="28sp"
            android:format24Hour="MMM dd, yyyy"
            app:layout_constraintTop_toBottomOf="@+id/textView" />
 </androidx.constraintlayout.widget.ConstraintLayout>


[![date_time_update_directly][1]][1]


  [1]: https://i.stack.imgur.com/JZWUj.png