0

I have a MainActivity, it has a lots of Fragment under it.

I set the return mechanism transaction.addToBackStack(null);

The function like this:

public void switchFragment(Fragment fragment) {
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.mainFrame, fragment, null);
    transaction.addToBackStack(null);
    transaction.commit();
}

My issue is when I click the back button to the end, the FrameLayout is white white screen

I tried to add

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {    
        if (mainFrame==null)
            return super.onKeyDown(keyCode, event);
    }
}

It's not working. How do I avoid this white screen when I call back the Fragment to the end ? Any help would be great!

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
Morton
  • 5,380
  • 18
  • 63
  • 118

2 Answers2

5

I took @ReazMushed's suggestion and changed like this:

@Override
public void onBackPressed() {
    if (getSupportFragmentManager().getBackStackEntryCount() ==1) {
        finish();
    }else{
        super.onBackPressed()
    }
}

And the white screen problem is gone!

Amila
  • 13
  • 6
Morton
  • 5,380
  • 18
  • 63
  • 118
2

From your question what I've understood is, you have a set of Fragment which is launched one after one and when you press the back button, they disappears one after one. When the first Fragment reaches and you click the back button again, it shows a white screen.

If I'm correct, you might have to track if the first Fragment is reached and then finish the Activity.

Implement the onBackPressed function in your MainActivity. You might consider doing something like this.

@Override
public void onBackPressed() {
    if (getSupportFragmentManager().getBackStackEntryCount() > 0)
        getSupportFragmentManager().popBackStack();
    else
        finish();    // Finish the activity
}
Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
  • Yes , you are correct ,thanks for your help , but it still shows a white screen when the first Fragment reaches – Morton Jan 23 '17 at 04:02
  • i found the way from your suggestion , i change like this 'if(getSupportFragmentManager().getBackStackEntryCount() ==1) { finish(); }' , i avoid the white screen issue now , although i 'm not sure it's the correct solution. – Morton Jan 23 '17 at 04:07