2014-10-30 72 views
0

儘管獲取當前日期時間的實例適用於啓動我的活動時,如果我轉到另一個屏幕並單擊後退按鈕返回到我之前的活動,日期時間與我第一次訪問活動時保持不變。另外,如果我保持空閒狀態,時間也不會更新。是因爲我只接收日期時間的一個實例嗎?我怎樣才能防止這一點?爲什麼我現在的日期時間並不總是與系統時鐘同步?

內活動:

long currentDateTime = System.currentTimeMillis(); 
Date date = new Date(currentDateTime); 

SimpleDateFormat format = new SimpleDateFormat("HH:mm"); 
String formatDate = format.format(date); 

TextView currentDateTextView = ((TextView) findViewById(R.id.current_datetime)); 
currentDateTextView.setText(formatDate); 

SimpleDateFormat formatLong = new SimpleDateFormat("EEE, MMMM d"); 
String formatDateLong = formatLong.format(date); 

TextView currentDateLongTextView = ((TextView) findViewById(R.id.current_datetime_long)); 
currentDateLongTextView.setText(formatDateLong); 

編輯:

即使我把上面的是我的onResume()方法,我仍然有問題:

如果我留在屏幕上,時間是靜態的,不會隨我的系統時間更新。我在那件事上做了什麼?

+1

將該代碼放入onResume方法。 – 2014-10-30 13:16:21

+0

哦,我會嘗試。現在,我只有在onCreate() – 2014-10-30 13:16:51

+2

onCreate使用後退按鈕時不會調用(onBackPressed) – 2014-10-30 13:17:50

回答

1

我用TextClock代替

<TextClock 
    android:id="@+id/current_datetime" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:format24Hour="HH:mm" 
    android:format12Hour="HH:mm" /> 

和它的作品就好了!我以前不知道TextClock小部件。

相關問題