Rag*_*ood 147
您创建的每个Activity都是通过一系列方法调用启动的.onCreate()是这些电话中的第一个.
您的每个活动android.app.Activity都可以直接扩展,也可以通过继承子类的其他子类扩展Activity.
在Java中,当您从类继承时,可以覆盖其方法以在其中运行您自己的代码.一个非常常见的例子是toString()扩展时覆盖方法java.lang.Object.
当我们覆盖一个方法时,我们可以选择完全替换我们类中的方法,或者扩展现有的父类方法.通过调用super.onCreate(savedInstanceState);,除了父类的onCreate()中的现有代码之外,还要告诉Dalvik VM运行代码.如果省略此行,则只运行您的代码.完全忽略现有代码.
但是,你必须在你的方法中包含这个超级调用,因为如果你不这样做,那么onCreate()代码Activity就永远不会运行,你的应用程序会遇到各种各样的问题,例如没有为Activity分配上下文(尽管你会点击a SuperNotCalledException在你有机会弄清楚你没有上下文之前).
简而言之,Android自己的类可能非常复杂.框架类中的代码处理诸如UI绘图,房屋清理以及维护活动和应用程序生命周期等内容.super调用允许开发人员在幕后运行这个复杂的代码,同时仍然为我们自己的应用程序提供良好的抽象级别.
*派生类onCreate(bundle)方法必须调用该方法的超类实现。如果未使用“ super ”关键字,它将抛出异常SuperNotCalledException。
对于in继承Java,要覆盖超类方法并执行上述类方法,请super.methodname()在覆盖派生类方法中使用;
Android 类的工作方式相同。通过扩展Activity具有onCreate(Bundle bundle)编写有意义代码的方法的类并在定义的活动中执行该代码,将 super 关键字与方法 onCreate() 一起使用,例如super.onCreate(bundle)。
这是一段用 Activity 类onCreate()方法编写的代码,Android 开发团队可能会在稍后为该方法添加一些更有意义的代码。因此,为了反映添加的内容,您应该在类中调用super.onCreate()Activity。
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.
*/
Run Code Online (Sandbox Code Playgroud)
它还维护变量mCalled,这意味着您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()");
}
}
Run Code Online (Sandbox Code Playgroud)
在此处查看源代码。