考虑以下情形:
类 TemplateActivity
扩展活动
。在 onResume()
将执行一个布尔变量的确认,然后,如有虚假,它完成的方法和活动,并开始一个新的活动, OtherActivity
。
在类 ChildActivity
,它扩展了 TemplateActivity
,运行时,它会等待超.onResume()
来完成,然后继续无论其超强的需要启动意图
与否。
的问题:
有没有一种方法来终止 ChildActivity
在 OtherActivity
需要从启动TemplateActivity
?无须在子类中的有效性检查。
超类:
类TemplateActivity延伸活动{
@覆盖
保护无效onResume(){
super.onResume();
如果(!初始化)
{
startActivity(新意图(这一点,OtherActivity.class));
完();
返回;
}
//做的东西
}
}
子类:
类ChildActivity扩展TemplateActivity {
@覆盖
保护无效onResume(){
super.onResume();
//做的东西
}
}
解决方案
一个更好的解决方案将是一个稍微不同的方法,以一流的设计:
在介绍的方法 DoStuff()
(与合理的名字替换)在 TemplateActivity
。难道所有的 //做的东西的位在那里。
从 TemplateActivity OnResume
的末尾调用此方法
覆盖它的子活动将其与子活动延长的 //做的东西的位。
请的没有的覆盖 onResume
在ChildActivity。
这样,如果在TemplateActivity OnResume条件火灾,没有父母和孩子DoStuff将完成。该 ChildActivity
不应该知道的什么的有关此问题。
Consider the following scenario:
The class TemplateActivity
extends Activity
. Within onResume()
it performs a validation of a boolean variable then, if false, it finishes the method and the activity, and starts a new activity, OtherActivity
.
When the class ChildActivity
, which extends TemplateActivity
, runs, it waits for super.onResume()
to finish and then continue no matter if its super needs to start the Intent
or not.
The question:
Is there a way to terminate the ChildActivity
when the OtherActivity
needs to start from the TemplateActivity
? Without implementing the validity check in the child class.
Superclass:
class TemplateActivity extends Activity {
@Override
protected void onResume() {
super.onResume();
if(!initialized)
{
startActivity(new Intent(this, OtherActivity.class));
finish();
return;
}
//Do stuff
}
}
Subclass:
class ChildActivity extends TemplateActivity {
@Override
protected void onResume() {
super.onResume();
//Do stuff
}
}
解决方案
A more elegant solution would be a slightly different approach to the class design:
Introduce a methodDoStuff()
(replace with sensible name) in the TemplateActivity
. Do all the // do stuff bits there.
Call this method from the end of TemplateActivity OnResume
Override it in the child activity to extend it with the child activity // do stuff bits.
Do not override onResume
in the ChildActivity.
This way, if the condition fires in TemplateActivity OnResume, none of the parent and child DoStuff will be done. The ChildActivity
shouldn't have to know anything about this behavior.
上一篇:称为AlarmManager通知活动不弹出,当应用程序被关闭弹出、应用程序、通知、AlarmManager
下一篇:NoClassDefFoundError的机器人与ActionBarActivity人与、机器、NoClassDefFoundError、ActionBarActivity