【问题标题】:what is the impact of code if we write before or after super() function in override function如果我们在 override 函数中写在 super() 函数之前或之后,代码会有什么影响
【发布时间】:2015-11-24 16:45:04
【问题描述】:
我对覆盖函数中的 super() 函数调用感到困惑。
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
在super.onDestroy() 之前或之后编写的代码有什么影响或
super.onPause()或android中所有类型的覆盖方法中的其他超级函数?
【问题讨论】:
标签:
android
android-activity
onpause
activity-lifecycle
ondestroy
【解决方案1】:
一般来说,允许基类初始化 first 并销毁 last 是一种很好的做法 - 这样,派生类所依赖的基类的任何初始状态都将已经被首先整理出来,相反,任何派生类清理代码都可以依赖仍然有效的基类数据。
在 Android 中,我将此行为扩展到 onPause 和 onResume:
@Override
protected void onCreate(Bundle savedInstanceState) {
// let Android initialise its stuff first
super.onCreate();
// now create my stuff now that I know any data I might
// need from the base class must have been set up
createMyStuff();
}
@Override
protected void onDestroy() {
// destroy my stuff first, in case any destroying functionality
// relies upon base class data
destroyMyStuff();
// once we let the base class destroy, we can no longer rely
// on any of its data or state
super.onDestroy();
}
@Override
protected void onPause() {
// do my on pause stuff first...
pauseMyStuff()
// and then tell the rest of the Activity to pause...
super.onPause();
}
@Override
protected void onResume() {
// let the Activity resume...
super.onResume();
// and then finish off resuming my stuff last...
resumeMyStuff();
}
实际上,onPause() 和 onResume() 并没有真正受到订单的影响,因为它们对活动状态的影响很小。但是确保创建和销毁遵循 base-create-first,base-destroy-last 的顺序非常重要。
但是,规则的例外总是存在的,一个常见的例外是,如果您想在 onCreate() 方法中以编程方式更改 Activity 的主题,则必须在调用 super.onCreate() 之前进行 .