I have a MainActivity in which I load different fragments (just one at the same time).
I have implemented HomeAsUp too, and it works well, but when I open a fragment, the back arrow appears at the left-top corner , but if I change the screen orientation, hamburger menu appears. I think that when activity is destroyed on the screen orientation change, the fragment backstack is also destroyed, how can i avoid this?
MAIN ACTIVITY
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private HashMap<String, String> connectedUserDataMap;
private FloatingActionButton fab;
private TextView textAccountName;
private ImageView profileImage;
private Bitmap profileImageBitmap;
private boolean doubleBackToExitPressedOnce = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) { //Main menu
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
//listener onBackStackChangedListener
getSupportFragmentManager().addOnBackStackChangedListener(new
FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
//show hamburger
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
}
}
});
}
In the fragment I have nothing related to this issue to show, just a fragment
EDIT 1:
I am doing some System.out.printlns in the fragment
System.out.println("BACKSTACK COUNT =
"+getActivity().getSupportFragmentManager().getBackStackEntryCount());
I can see that getBackStackEntryCount() = 1 but the code in my MainActivity does not execute cause the backstack has not changed and does not print the back arrow
The Issue is that when I open the fragment the back arrow is at the left top corner, but when I rotate the screen, hamburger menu appears when It should not
SOLVED: I just put the code associated with the OnBackStackChangedListener in the MainActivity oncreate method too!
Thanks to all!