2011-08-10 30 views
4

我試圖測試UI和Timer類的可能性。所以,我想下面的練習:從TimerTask的運行方法更新TextView時出錯

=== TestTimerActivity.java ===

package com.tvt.TestTimer; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.TextView; 
import java.util.Timer; 
import java.util.TimerTask; 


public class TestTimerActivity extends Activity { 
    TextView _tv; 
    Timer _t; 
    int _count = 0; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     // 

//  _tv = (TextView) getWindow().getDecorView().findViewById(R.id.TextViewTime); 

     _tv = (TextView) findViewById(R.id.TextViewTime); 

     UpdateTime(); // Completes OK 

     _t = new Timer(); 

     _t.scheduleAtFixedRate(new TimerTask() { 
      @Override 
      public void run() { 
       // TODO Auto-generated method stub 
       _count++; 
       UpdateTime(); // Fails 
      } 
     }, 1000, 1000); 
    } 

    protected void UpdateTime() { 
     _tv.setText("" + _count); 
    } 
} 

=== TestTimerActivity.java ===

=== main.xml中===

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
<TextView 
    android:layout_width="fill_parent" 
    android:gravity="center_horizontal" android:layout_height="wrap_content" android:layout_gravity="center" android:text="@string/header" android:id="@+id/TestViewHeader" android:textStyle="bold"/> 
<TextView android:layout_height="wrap_content" android:id="@+id/TextViewTime" android:layout_width="match_parent" android:layout_gravity="center_horizontal" android:gravity="center_horizontal" android:text="-"></TextView> 
</LinearLayout> 

=== main.xml中===

的第一個電話更新時間(從的onCreate)完成確定的,但同樣的來自TimerTask :: run()的調用未能給出消息「TestTimer類已意外停止」。

有什麼想法?我的錯在哪裏?

-
SY,TVT

+0

張貼您的logcat .. – ngesh

回答

11

做的UI線程上UpateTime()操作。

protected void UpdateTime() 
{ 
    runOnUiThread(new Runnable() 
    { 
    public void run() 
    { 
      _tv.setText("" + _count); 
     } 
    }); 
} 

希望能解決您的問題。

1

從UI /主線程以外的線程更新UI將失敗,因爲Android不允許。嘗試使用Handler將消息發佈回UI線程。

或者可能嘗試使用AsyncTask,它提供了一組真正簡單的回調方法來處理工作線程和UI線程。但是,這可能不是你所需要的,因爲你試圖測試TimerTask類。

+0

**非常感謝**,_guys_!我會試試看!我是C++開發人員,事實證明,找到系統的Android開發指南並不容易。有沒有? – FILEAHOLIC

+0

最好的指南是官方文檔http://developer.android.com/ –

+1

@Fileaholic:從個人經驗來看,首先適應Java,然後繼續與Android合作可能是一個好主意。一旦你有了這個目標,就選擇一個目標,然後建立它,找出你需要的任何東西。學習這種方式會更簡單,尤其是因爲您會犯很多錯誤,並且您將學習如何更好地使用Android。 – Archit