作为初学者,有人可以解释一下上述代码行的目的吗?
您每进行一项活动,都会通过一系列方法调用来启动。其中onCreate()
是这些调用中的第一个。
您的每个Activity都直接或通过其他Activity
的子类扩展android.app.Activity
。
在Java中,当您从一个类继承时,可以重写其方法以运行自己的代码。这种情况非常普遍,例如在扩展java.lang.Object
时覆盖toString()
方法。
当我们重写一个方法时,我们可以选择完全替换类中的方法,也可以扩展现有父类的方法。通过调用super.onCreate(savedInstanceState);
,您告诉Dalvik VM在父类的onCreate()
中运行您的代码以及现有代码。如果省略此行,则只运行您的代码。现有代码将被完全忽略。
但是,您必须在自己的方法中包含此超级调用,因为如果不这样做,则Activity
中的onCreate()
代码永远不会运行,您的应用程序将遇到各种问题,例如未分配给活动的上下文(虽然在发现没有上下文之前,您将遇到SuperNotCalledException
)。
简而言之,Android的本身的类可以非常复杂。框架类中的代码处理UI绘制、清理和维护Activity和应用生命周期等问题。super
调用允许开发人员在幕后运行此复杂代码,同时为我们自己的应用程序提供良好的抽象程度。
onCreate(bundle)
方法必须调用超类实现此方法。如果没有使用"super"关键字,它将抛出异常SuperNotCalledException。
在Java中进行继承,要重写超类方法并执行上述类方法,在覆盖的派生类方法中使用super.methodname()
;
Android类也是这样工作的。通过扩展具有onCreate(Bundle bundle)
方法的Activity
类,在其中编写有意义的代码,并使用带有super.onCreate(bundle)
的onCreate()方法来执行定义的活动中的代码。
这是Activity类onCreate()
方法中的一段代码,Android Dev团队可能会稍后添加更多有意义的代码到这个方法中。因此,为了反映这些新增内容,你应该在你的Activity
类中调用super.onCreate()。
protected void onCreate(Bundle savedInstanceState) {
mVisibleFromClient = mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, true);
mCalled = true;
}
boolean mVisibleFromClient = true;
/**
* Controls whether this activity main window is visible. This is intended
* only for the special case of an activity that is not going to show a
* UI itself, but can't just finish prior to onResume() because it needs
* to wait for a service binding or such. Setting this to false prevents the UI from being shown during that time.
*
* <p>The default value for this is taken from the
* {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
*/
mCalled
,这意味着您在 Activity 中调用了 super.onCreate(savedBundleInstance)
。final void performStart() {
mCalled = false;
mInstrumentation.callActivityOnStart(this);
if (!mCalled) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onStart()");
}
}
在这里查看源代码。
如果由于某些隐含原因(例如不是用户按下返回按钮)而导致活动被销毁并重新启动,您希望通过onCreate()将信息返回到应用程序。 onSaveInstanceState()的最常见用途是处理屏幕旋转,因为默认情况下,当用户滑出G1键盘时,活动会被销毁并重新创建。
调用super.onCreate(savedInstanceState)的原因是否则您的代码将无法编译。 ;-)
super.onCreate(savedInstanceState)
,它也会编译成功。 - Raghav Sood