Skip to content

Instantly share code, notes, and snippets.

@EduardoSP6
Last active December 13, 2023 16:08
Show Gist options
  • Save EduardoSP6/29c5388617b863503a2b0a9bfdb1dbdd to your computer and use it in GitHub Desktop.
Save EduardoSP6/29c5388617b863503a2b0a9bfdb1dbdd to your computer and use it in GitHub Desktop.
Show back button in Toolbar from Fragment in Android App
# In this situation I have the MainActivity that calls FragmentA. This fragment implements OnBackStackChangedListener,
# and checks the size of the backStack; if it's less than one, then it hides the UP button. The fragments B and C are called by
# the A, them just show/hide the button.
# MainActivity:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getSupportFragmentManager().popBackStack();
return true;
}
return super.onOptionsItemSelected(item);
}
public void showUpButton() { getSupportActionBar().setDisplayHomeAsUpEnabled(true); }
public void hideUpButton() { getSupportActionBar().setDisplayHomeAsUpEnabled(false); }
# Fragment A:
public class FragmentA extends Fragment implements FragmentManager.OnBackStackChangedListener {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// listen to backstack changes
getActivity().getSupportFragmentManager().addOnBackStackChangedListener(this);
}
public void onBackStackChanged() {
if(getActivity() != null) {
// enable Up button only if there are entries on the backstack
if(getActivity().getSupportFragmentManager().getBackStackEntryCount() < 1) {
((MainActivity)getActivity()).hideUpButton();
}
}
}
...
}
# Fragments B and C:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// displays the back button on toolbar
((MainActivity)getActivity()).showUpButton();
}
@prak899
Copy link

prak899 commented Dec 13, 2023

can you please give more context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment