Jayyrus
Jayyrus

Reputation: 13051

How to choose which fragment must be shown on backpressed

Hi i'm trying problem when i use onBackPressed with fragments:

if add fragment in this way:

public void showFragment(Fragment new_fragment,String tag,boolean back){
    FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentByTag(tag);
    fragment = fragment==null?new_fragment:fragment;
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, fragment);
    if(back)transaction.addToBackStack(tag);
    transaction.commit();
}

@Override
public void onBackPressed() {
   FragmentManager fm = getSupportFragmentManager();
   FragmentTransaction ft = fm.beginTransaction();
   if (fm.getBackStackEntryCount() > 0) {
            fm.popBackStack();
   }else {
        moveTaskToBack(true);
   }
}

When i use popBackStack fragments will be overlapped. Why?

How can i remove correctly or avoid to store on backstack fragments that i don't need ( for example SplashScreenFragment )?

Thanks!

Upvotes: 0

Views: 97

Answers (1)

Stan Smith
Stan Smith

Reputation: 906

Your showFragment() function has a parameter (boolean back) than can exclude it from the stack.

You could also use one of the other popBackStack() method signatures that pop back to a given identifier (http://developer.android.com/reference/android/app/FragmentManager.html)

Or you could use NavUtils and manifest definitions for defining relationships.

Upvotes: 1

Related Questions