2013-04-22 52 views
0

我一直在試圖創建一個程序,它將輸出一個可以讓我快速訪問日期和時間的工作數字時鐘。我有解析時間的代碼,但是,我很難更新textview。我有這個:用時鐘更新TextView

`public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    timer = (TextView)findViewById(R.id.timer); 

    time = new Time(); 
    time.setToNow(); 

    timeString = time.toString(); 
    changeTime = Parser(timeString); 


    time.setToNow(); 
    timeString = time.toString(); 
    changeTime = Parser(timeString); 

    timer.setText(changeTime); 
    } 
    private String Parser(String time){ 

    String year = time.substring(0, 4); 
    String month = time.substring(4,6); 
    String day = time.substring(6, 8); 
    String hour = time.substring(9,11); 
    String minute = time.substring(11, 13); 
    String second = time.substring(13, 15); 

    String finalTime = hour + ":" + minute + ":" + second + " " + day + " " + month + " " + year; 
    //String finalTime = second; 
    return finalTime; 


}` 

我如何把它放在一個循環中不斷更新textview。

感謝您給我的任何幫助。

+0

你可以使用'Thread','TimerTask'或'Handler.postdelayed'更新的TextView不斷,而不是使用循環 – 2013-04-22 18:23:20

回答

0

聲明一個處理程序來更新UI線程上的TextView。

private Handler mHandler = new Handler() { 
@Override 
public void handleMessage(Message msg) { 
    time = new Time(); 
    time.setToNow(); 

    timeString = time.toString(); 
    changeTime = Parser(timeString); 
    timer.setText(changeTime); 
} 
}; 

啓動TimeTask,將更新的TextView

int initialDelay = 1000; //first update in miliseconds 
int period = 5000;  //nexts updates in miliseconds  

Timer timer = new Timer(); 
TimerTask task = new TimerTask() { 
    public void run() { 
     Message msg = new Message(); 
     mHandler.sendMessage(msg); 
    } 
}; 
timer.scheduleAtFixedRate(task, initialDelay, period); 
+0

這個工作,謝謝你真是太棒了! – JJJ1106 2013-04-23 15:00:54

1

你應該使用一個計時器線程。您還可以使用Calendar簡化時間和日期轉換,並可以使用format來優化字符串創建。這個例子將更新TextView每秒(1000毫秒):

Timer t = new Timer(); 
timer = (TextView)findViewById(R.id.timer); 

t.scheduleAtFixedRate(new TimerTask() 
{ 
    @Override 
    public void run() { 
     Calendar c = Calendar.getInstance(); 
     String finalTime = String.format(Locale.US, "%d:%d:%d %d/%d/%d", c.get(Calendar.HOUR), c.get(Calendar.MINUTE), c.get(Calendar.SECOND), c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH), c.get(Calendar.YEAR)); 

     runOnUiThread(timer.setText(finalTime)); 
    } 

}, 1000); 
+0

這似乎使格式化的時間出現,但它似乎並沒有更新。任何我可能做錯的想法? – JJJ1106 2013-04-23 14:56:56

+1

@ JJJ1106,是的 - 我修復了我的帖子。您需要在'TimerTask'內創建'Calendar'實例。如果這適合你,請考慮接受這個答案,因爲它很簡單。 – Phil 2013-04-23 17:44:53

0

這可以很容易用一個線程在機器人的幫助下進行,但是,你要訪問的UI線程因此將無法正常工作的幫助你。你應該更好地選擇處理程序或TimerTask的

但是異步任務也非UI線程運行,從而使一個TimerTask內的處理程序..

Timer t=Timer(); 

    t.scheduleAtFixedRate(new TimerTask(new Runnable() 
     { 
    public void run(){ 
    Handler h=new Handler(getMainLooper()); 
    h.post(new Runnable(
){public void run(){ 
//get the time here and set the textview here as here it has access to the main ui 
}}); 
    } 
    } 
    ), long delay, Long period); 

對不起壞的代碼格式...但它會爲工作你

0

開始用永不結束的處理程序消息更新視圖是不好的做法(試着看看你的進程的CPU級別)。 更好,更優雅的方式是註冊一個BroadcastReceiver這將觸發更新。

public class Clock extends LinearLayout { 

    private Calendar mCalendar; 
    private LinearLayout mLayoutTime; 
    private TextView mAMPMText; 
    private TextView mDateText; 
    private TextView mTimeText; 
    private View mSendFeedback; 
    private boolean mAttached; 

    private final Handler mHandler = new Handler(); 
    SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE, MMM d, yyyy"); 
    SimpleDateFormat timeFormatter = new SimpleDateFormat("h:mm"); 

    public Clock(final Context context, int layoutResourceID, int dateResId, int meResId,int amPmResId) { 
     super(context); 
     LayoutInflater layoutInflater = LayoutInflater.from(context); 
     View view = layoutInflater.inflate(layoutResourceID, null); 
     addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 
     mAMPMText = (TextView) view.findViewById(amPmResId); 
     mTimeText = (TextView) view.findViewById(timeResId); 
     mDateText = (TextView) view.findViewById(dateResId);  
    } 

    @Override 
    protected void onAttachedToWindow() { 
     super.onAttachedToWindow(); 

     if (!mAttached) { 
      mAttached = true; 
      IntentFilter filter = new IntentFilter(); 

      filter.addAction(Intent.ACTION_TIME_TICK); 
      filter.addAction(Intent.ACTION_TIME_CHANGED); 
      filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); 

      getContext().registerReceiver(mIntentReceiver, filter, null, mHandler); 
     } 

     // NOTE: It's safe to do these after registering the receiver since the receiver always runs 
     // in the main thread, therefore the receiver can't run before this method returns. 

     // The time zone may have changed while the receiver wasn't registered, so update the Time 
     mCalendar = Calendar.getInstance(); 

     // Make sure we update to the current time 
     onTimeChanged(); 
     updateView(); 
    } 

    @Override 
    protected void onDetachedFromWindow() { 
     super.onDetachedFromWindow(); 
     if (mAttached) { 
      getContext().unregisterReceiver(mIntentReceiver); 
      mAttached = false; 
     } 
    } 

    private void updateView(){ 
     mTimeText.setText(timeFormatter.format(mCalendar.getTime())); 
     mDateText.setText(dateFormatter.format(mCalendar.getTime())); 
     mAMPMText.setText(mCalendar.get(Calendar.AM_PM) == 0 ? "AM" : "PM"); 
    } 

    private void onTimeChanged() { 
     mCalendar.setTime(new Date()); 

     updateContentDescription(mCalendar); 
    } 

    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) { 
       String tz = intent.getStringExtra("time-zone"); 
       mCalendar.setTimeZone(TimeZone.getTimeZone(tz)); 
      } 

      onTimeChanged(); 

      updateView(); 
     } 
    }; 

    private void updateContentDescription(Calendar calendar) { 
     setContentDescription(calendar.toString()); 
    } 
} 

佈局(可以做的更好)

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="match_parent" 
    android:gravity="center_vertical" 
    android:orientation="horizontal" > 

    <LinearLayout 
     android:id="@+id/layout_time" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" > 

     <TextView 
      android:id="@+id/time_txt" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:includeFontPadding="true" /> 

     <TextView 
      android:id="@+id/am_pm_txt" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="AM" /> 
    </LinearLayout> 

    <TextView 
     android:id="@+id/date_txt" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

</RelativeLayout>