I am using a single Activity approach with a Navigation Graph. I don't want my tab layout or the toolbar visible in some fragments. I wrote a superclass to extend from in those fragments i don't want the bars. But somehow i do not understand the lifecycle correctly as this is not working:
public class NoTabLayoutFragment extends Fragment {
@Override
public void onResume() {
super.onResume();
hideTabLayout();
}
@Override
public void onPause() {
super.onPause();
showTabLayout();
}
private void showTabLayout() {
if (getActivity() != null && getActivity().findViewById(R.id.fragment_main_tab_layout) != null) {
getActivity().findViewById(R.id.fragment_main_tab_layout).setVisibility(View.VISIBLE);
}
}
private void hideTabLayout() {
if (getActivity() != null && getActivity().findViewById(R.id.fragment_main_tab_layout) != null) {
getActivity().findViewById(R.id.fragment_main_tab_layout).setVisibility(View.GONE);
}
}
}
and
public class NoBarsFragment extends NoTabLayoutFragment {
@Override
public void onResume() {
super.onResume();
hideToolbar();
}
@Override
public void onPause() {
super.onPause();
showToolbar();
}
private void hideToolbar() {
if (getActivity() != null && ((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
}
}
private void showToolbar() {
if (getActivity() != null && ((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
((AppCompatActivity) getActivity()).getSupportActionBar().show();
}
}
}
What am i doing wrong?
As per the Listen for Navigation Events documentation, the correct way to change UI visibility is via an OnDestinationChangedListener
:
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
@Override
public void onDestinationChanged(@NonNull NavController controller,
@NonNull NavDestination destination, @Nullable Bundle arguments) {
if(destination.getId() == R.id.full_screen_destination) {
getSupportActionBar().hide()
} else {
getSupportActionBar().show()
}
}
});