繁体   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