2012-11-12 56 views
1

當Digital Clock每分鐘刷新一次格式爲hh/mm的時間時,我想每分鐘刷新一次TextView的文本。我在活動中放置了一個名爲txtView1的TextView,並創建了一個類Digital Clock。當我運行該應用程序時,該應用程序退出時出現錯誤。我真的不知道爲什麼 這裏是關於數字時鐘的重要功能onAttachedToWindow()如何在Android數字時鐘期間刷新TextView?

protected void onAttachedToWindow() { 
     mTickerStopped = false; 

     super.onAttachedToWindow(); 

     mHandler = new Handler(); 


     /** 

     * requests a tick on the next hard-second boundary 

     */ 

     mTicker = new Runnable() { 

       public void run() { 

        if (mTickerStopped) return; 

        mCalendar.setTimeInMillis(System.currentTimeMillis()); 

        String content = (String) DateFormat.format(mFormat, mCalendar); 

        if(content.split(" ").length > 1){ 



         content = content.split(" ")[0] + content.split(" ")[1]; 

        } 

        setText(android.text.Html.fromHtml(content)); 

        //-----Here is the TextView I want to refresh 

        TextView txtV1 = (TextView)findViewById(R.id.txtView1); 
        txtV1.setText("Now Fresh");//Just for try,so set a constant string 

        invalidate(); 

        long now = SystemClock.uptimeMillis(); 

        //refresh each minute 

        long next = now + (60*1000 - now % 1000); 

        mHandler.postAtTime(mTicker, next); 

       } 

      }; 

     mTicker.run(); 

    } 
+0

看看這可以幫助你http://stackoverflow.com/questions/5188295/how-to-change-a-textview-every-second-in-android –

回答

0

系統根據系統時鐘在每分鐘的確切開始處發送廣播事件。最可靠的辦法是做這樣的:

BroadcastReceiver _broadcastReceiver; 
private final SimpleDateFormat _sdfWatchTime = new SimpleDateFormat("HH:mm"); 
private TextView _tvTime; 

@Override 
public void onStart() { 
    super.onStart(); 
    _broadcastReceiver = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context ctx, Intent intent) { 
       if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0) 
        _tvTime.setText(_sdfWatchTime.format(new Date())); 
      } 
     }; 

    registerReceiver(_broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK)); 
} 

@Override 
public void onStop() { 
    super.onStop(); 
    if (_broadcastReceiver != null) 
     unregisterReceiver(_broadcastReceiver); 
} 

但是不要忘了事先初始化你的TextView(爲當前系統時間),因爲很可能你會彈出一分鐘的中間你的用戶界面和TextView將不會更新,直到下一分鐘發生。