问题
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
}
}
回答1:
A more elegant solution would be a slightly different approach to the class design:
- Introduce a method
DoStuff()
(replace with sensible name) in theTemplateActivity
. 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.
回答2:
I guess this is what you're trying to get:
class ChildActivity extends TemplateActivity {
@Override
protected void onResume() {
super.onResume();
if (!isFinishing()) {
// Do stuff
}
}
}
来源:https://stackoverflow.com/questions/12696149/finish-subclass-activity-from-its-superclass