【问题标题】:An always open app showing the current date and time一个始终打开的应用程序,显示当前日期和时间
【发布时间】:2020-02-26 10:18:58
【问题描述】:

我正在制作一个将始终在我的平板电脑中打开的应用程序。我正在尝试实时显示当前日期和时间。目前,我使用以下代码

<DigitalClock
        android:id="@+id/digitalClock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:textColor="#FFFFFF"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintTop_toBottomOf="@+id/date"
        tools:layout_editor_absoluteX="0dp" />

而且效果很好。该应用程序始终处于打开状态,并且时间实时变化 (虽然我现在正在搜索如何添加秒数)

对于日期,我使用了那个代码

dateTimeDisplay = (TextView)findViewById(R.id.date);
calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, dd MMMM, yyyy");
date = dateFormat.format(calendar.getInstance().getTime());
dateTimeDisplay.setText(date);

但它显示的是当前日期,而不是实时的。只有当我打开应用程序时它才会改变。

我可以知道,因为我在 dateFormat 中输入了秒数来测试它,它是静态的。

SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, dd MMMM, yyyy , ss");

有人知道吗?谢谢!!

【问题讨论】:

  • 顺便考虑一下扔掉长期过时且臭名昭著的麻烦SimpleDateFormat和朋友,并将ThreeTenABP添加到您的Android项目中,以便使用java.time,现代Java日期和时间API .使用起来感觉好多了。
  • 如果有帮助请记住接受答案(如果没有帮助则不要接受)。谢谢。

标签: android date calendar


【解决方案1】:

DigitalClock 已被弃用,建议您改用TextClock

TextClock 默认会完成你的工作。检查下面的例子

<TextClock
        android:id="@+id/textClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:format12Hour="hh:mm:ss a"
        android:textColor="#F1511B"
        android:textSize="45dp"
        android:textStyle="bold" />

对于 24 小时格式,请使用

android:format24Hour="hh:mm:ss a

Improvement note: 您应该使用ThreeTenABP 作为 Ole V.V.,而不是使用 SimpleDateFormat 和帮助程序类。在评论中表示。这里是How to use ThreeTenABP in Android Project

【讨论】:

  • 谢谢你,我会做出改变的。你对日期有什么想法吗?
  • 我刚刚进行了更改,但显示相同..只有小时和分钟..不是秒..但至少它是实时的..
  • 我将其更改为 android:format24Hour="hh:mm:ss a" 并且有效!再次感谢您!
猜你喜欢
  • 2011-01-17
  • 1970-01-01
  • 2012-07-23
  • 2014-06-10
  • 1970-01-01
  • 2014-01-15
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多