What is going on with my Android Navigation drawer activity?
In your onNavigationItemSelected
method, you are replacing the current fragment with fragment
even in cases where fragment
is null, which has undefined effects. You should not do that.
One fix is to replace this code block:
try { fragment = (Fragment) fragmentClass.newInstance();} catch (Exception e) { e.printStackTrace();}
with this one:
if (fragmentClass != null) { fragment = fragmentClass.newInstance(); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).addToBackStack().commit();}
(and then leave out the fragment transaction below this point).
Also, there is a call to finish
in the onDestroy
method, which probably is not causing the problem but should be taken out because it does not make any sense there.
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); break; } return true; }
replace your onOptionsItemSelected() with mine.
Don't include your first fragment into backstack.
Try to change you fragment transaction line code without addToBackStack
as below:
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
While adding fragment with
addToBackStack
, this allows back navigation for added fragment.Because of fragment in backstack, empty(black) activity layout will be displayed.
Change onBackPressed()
as below which automatically close app after if no any Fragment found in FragmentManager:
@Overridepublic void onBackPressed() { if (getSupportFragmentManager().getBackStackEntryCount() == 0) { this.finish(); } else { getSupportFragmentManager().popBackStack(); }}
Also you can see some similar Q/A on below links which helps you get more idea to solve your problem:
In Fragment on back button pressed Activity is blank
Transaction of fragments in android results in blank screen
It's solved my blank screen problem. Hope its helps you.