簡體   English   中英

如何在 Android Studio 中將實時 DateTime 顯示為 textView(如數字手表)?

[英]How to show the live DateTime as a textView (Like a digital watch) in Android Studio?

我在xml文件中制作了兩個textView文件,其中一個textView顯示當前日期,另一個顯示當前時間為text

現在,我使用了 java Calendar.getInstance().getTime()方法來獲取日期和時間信息。 但它充當 static 視圖,即它不會像數字時鍾那樣更改日期和時間。

現在我正在嘗試顯示textViews以顯示與設備系統的日期和時間同步的當前日期和時間。 這意味着,假設現在是晚上11:59:59 PM ,日期是7th Sep, 2022 就在1s之后,我的時間textView應該顯示時間為12:00:00 AM ,日期應該顯示為8th Sep, 2022 並且它應該像數字時鍾一樣在每1s秒后繼續更改時間。 最后,系統日期時間和應用程序日期時間之間不應有任何延遲,即完美同步。

怎么做??

public class MainActivity extends AppCompatActivity {

    TextView textDate, textClock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textDate = findViewById(R.id.textDate);
        textClock = findViewById(R.id.textClock);
        setDateTime();
    }

    private void setDateTime() {
        Date c = Calendar.getInstance().getTime();
        SimpleDateFormat df = new SimpleDateFormat("dd MMM, yyyy", Locale.getDefault());
        SimpleDateFormat df_clock = new SimpleDateFormat("hh:mm:ss a", Locale.getDefault());
        String formattedDate = df.format(c);
        String formattedClock = df_clock.format(c);

        textDate.setText(formattedDate);
        textClock.setText(formattedClock);
    }
}

Android 中已經有一個TextClock class ,您應該可以使用它。 嘗試用這些替換您的兩個TextView 並將格式設置為您的模式。

您需要設置一個后台線程,該線程將要求 UI 每秒更新一次。

我想是這樣的(但我不知道這有多准確)

private void blink() {
      final Handler hander = new Handler();
      new Thread(new Runnable() {
         @Override
         public void run() {
            // off the UI
            try {
               Thread.sleep(1000);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
            // back ot the UI
            hander.post(new Runnable() {
               @Override
               public void run() {
                  // notify the UI here
                  blink();
               }
            });
         }
      }).start();
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM