Finish parent and current activity in Android

前端 未结 16 3102
误落风尘
误落风尘 2020-11-27 03:40

I have 3 activities. Activity A which leads to activity B, which in turn can go back to activity A or start activity C. However, if I press back in activity C the app should

16条回答
  •  情话喂你
    2020-11-27 04:06

    You can just override the back key behavior:

    Activity A starts activity B
    Pressing Back on activity B should lead to A
    Activity B starts activity C
    Pressing Back on activity C should close the app

    Note that I don't call super from onBackPressed. This also allows you to override the browse stack mechanism for Android, which I find to be a big advantage, since currently there doesn't seem to be a way to clear the single oldest item from the browse stack in a simple way.

    public class B extends Activity
    {
        ...
        @Override
        public void onBackPressed()
        {
            // Start activity A
            Intent aIntent = new Intent(this, A);
            startActivity(bIntent);
        }
        ...
    }
    
    public class C extends Activity
    {
        ...
        @Override
        public void onBackPressed()
        {
            // Close
            finish();
        }
        ...
    }
    

    You can specifically finish the parent activity if needed too, but using this method, you don't have to worry about it.

提交回复
热议问题