Finish subclass activity from its superclass

2019-08-03 06:56发布

问题:

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:

  1. Introduce a method DoStuff() (replace with sensible name) in the TemplateActivity . Do all the // do stuff bits there.
  2. Call this method from the end of TemplateActivity OnResume
  3. Override it in the child activity to extend it with the child activity // do stuff bits.
  4. 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 ChildActivityshouldn'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
        }
    }
}