簡體   English   中英

在方法中聲明時可運行的作品; 在方法外聲明時崩潰

[英]Runnable works when declared in method; crashes when declared outside of method

我是Android新手。

我想在幾秒鍾后修改我的活動的TextView(首先說“嘿,嘿!”;幾秒鍾后我想說“你好!”),所以我有:

protected void onResume() {
    super.onResume();

    final TextView t = (TextView)findViewById(R.id.hello);
    Runnable changeTextTask = new Runnable() {
        public void run() {
            t.setText("hello!");
        }
    };

    Handler h = new Handler();
    h.postDelayed(changeTextTask, 3000);
}

哪個有效。 但是,當我在課程開始時聲明Runnable時,如下所示:

public class MainActivity extends ActionBarActivity {
    final TextView t = (TextView)findViewById(R.id.hello);
    Runnable changeTextTask = new Runnable() {
        public void run() {
            t.setText("hello!");
        }
    };

    .
    .
    .

    protected void onResume() {
        super.onResume();

        Handler h = new Handler();
        h.postDelayed(changeTextTask, 3000);
    }

該應用程序在啟動時崩潰。 誰能解釋為什么會這樣/我在做什么錯?

我做錯了什么?

首先, 使用LogCat檢查崩潰的Java堆棧跟蹤。

其次,不要在Activity上調用繼承的方法,例如findViewById() ,直到onCreate()內部,並且通常在super.onCreate()調用之后。 onCreate()完成之后調用onResume() ,這就是為什么您的第一版可以更好地onCreate()原因。

第三,特別是使用findViewById() ,您需要在小部件已經存在之后調用它。 直到setContentView()或用於設置UI的等效方法后,這種情況才會發生。

在這里混合了Sotirios Delimanolis和CommonsWare的響應:

LogCat顯示findViewByID()導致NullPointerException,因為在活動開始后就在onCreate()(帶有TextView的資源已加載到其中)之前調用了它。

暫無
暫無

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

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