Skip to content
Advertisement

On Activity App Bar back pressed go to the parent activity with the fragment it was called

I’m having an issue that maybe is happening to other community members and I wanted to ask if somebody knows the solution. I have an app with these Two activities (MainActivity, UserProfileActivity).

The MainActivity contains a NavigationDrawer that navigates through fragments. So here it’s the problem. While navigating in the second fragment and pressing a button in that fragment. It opens the UserProfileActivity (child of MainActivity) with the app bar generated by being a child. When you press that back button of this new Activity it should get back to MainActivity (parent) in the fragment that we were when we called this new Activity. But not, it’s getting back to the MainActivity but with the home fragment loaded. Not the one we called previously.

Does anybody know how to solve that problem? Here I leave the code of the intent I do from the fragment:

Intent intent = new Intent(context, UserProfileActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("userId", message.getUserId());
            intent.putExtras(bundle);
            context.startActivity(intent);

Advertisement

Answer

Reason behind this behavior:

If you set the value of android:parentActivityName in your manifest.xml, by default pressing navigation button will create a new instance of the parent activity every time rather than popping it out from the activity backstack, so you’re seeing the home fragment.

Workaround

At first, remove android:parentActivityName from manifest.xml. In onCreate method of your ChildActivity, put getSupportActionBar().setDisplayHomeAsUpEnabled(true) if you haven’t already. Then override onSupportNavigateUp() of your ChildActivity, and put finish().

ChildActivity.java:

public class ChildActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        getSupportActionBar().setDisplayHomeAsUpEnabled(true)
        ...
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return super().onSupportNavigateUp();
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement