0

我在 Activity 的 onCreate() 方法中创建了一个按钮,并尝试在 onRestoreInstanceState(Bundle) 方法中更改按钮的状态。我在这种方法中只有一行。

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
savedButton.setSelected(true);
super.onRestoreInstanceState(savedInstanceState);
}

但有时 java.lang.NullPointerException 异常发生在我更改按钮状态的这一行,有时它工作正常。

我哪里错了?

日志:

java.lang.NullPointerException
    at com.test.MainActivity.onRestoreInstanceState(MainActivity.java:35)
    at android.app.Activity.performRestoreInstanceState(Activity.java:934)
    at android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1145)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2088)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3576)
    at android.app.ActivityThread.access$800(ActivityThread.java:143)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4950)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
    at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

1

把这个

if(savedInstanceState != null) {
    savedButton.setSelected(true);
}

onCreate(Bundle savedInstanceState)您定义按钮后,改为您的。

于 2013-06-12T07:12:35.183 回答