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

11
我想在TextView中以09:41时分格式展示当前时间,并持续更新,有可能实现吗?我尝试过一些方法,但并没有得到我想要的结果。
6个回答

22

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源代码中窃取代码。这应该是相当简单的。


你能给我展示一个例子吗?如果可以的话,我会迅速接受你的答案! - Ajinkya More
这实际上很简单。它实际上是TextView的子类,可以为您完成所有操作。只需在XML设计器中单击并拖动到布局中即可。 - dabluck
但它需要API 17! - Ajinkya More
我找到了解决方案: Date d = new Date(); CharSequence s = DateFormat.format("hh:mm", d.getTime()); TextView tv = (TextView)findViewById(R.id.tv); tv.setText(s);但是如何更新这个时间呢?只要告诉这么多!!!拜托了!!! - Ajinkya More
让我们在聊天中继续这个讨论 - dabluck
显示剩余2条评论

15

这样做应该可以解决问题。

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,而在恢复后则要重新开始。


最后一个问题!如何将其设置为12小时格式? - Ajinkya More
@BojanKseneman 谢谢老兄,没有一个例子符合我对Service类的要求,但是你的代码非常完美地解决了我的问题! - RUTURAJ Raval
你可以使用android.text.format.DateUtils代替SimpleDateFormat。 - Brill Pappin
TextClock 允许做同样的事情 - https://developer.android.com/reference/android/widget/TextClock - Dory

3
  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();

我应该在 setContentView 之前调用 timer() 吗? - Ajinkya More
不要在 setContentView 方法调用之前操作 textView,因为定时器需要找到 textView,否则可能会出现 NullPoiterException 异常。在 setContentView 方法调用之后再操作它。 - Charaf Eddine Mechalikh
在我的代码中,更新时间为20秒(20000毫秒),您可以根据需要设置更新时间。 - Charaf Eddine Mechalikh
我想在后台服务中更新文本时钟时间,这是否可能? - Deep Rathod

3

如果需要直接使用自定义日期和时间:

  • 时间格式: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://istack.dev59.com/JZWUj.webp

2

为什么不使用Java的计时器和任务?它们非常易用、可靠且易于理解。

以下是一个示例:

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

我知道这里有一些要做的笔记,但任何有Java合理经验的安卓开发者都应该能够弄清楚如何完成这些事情。

希望这可以帮到你!

编辑 要将日期格式化为可视字符串,您可以使用以下代码(仅使用Java的已安装API)

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

Android不是实时操作系统,因此您不能依赖它在下一个计时器周期被调用时恰好为1000毫秒,而且您会将每个步骤中所做的时间误差积累起来:/ - Bojan Kseneman

1

要获取时间和日期,您可以使用 Calendar 类。

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

只是顺便提一下:在开发Android Things下的应用程序时,日历API将无法访问。 - Jviaches

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