Finish subclass activity from its superclass

落爺英雄遲暮 提交于 2019-12-11 09:26:14

问题


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
        }
    }
}


来源:https://stackoverflow.com/questions/12696149/finish-subclass-activity-from-its-superclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!