Last active
September 30, 2016 18:06
-
-
Save Metroxe/f753aa4fe6153869950689dd81c68be9 to your computer and use it in GitHub Desktop.
Fragment Backstack Recycling and Movement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Activity extends AppCompatActivity { | |
public String lastFragment; | |
private FragmentManager fragmentManager; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_onboarding); | |
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); | |
setSupportActionBar(toolbar); | |
fragmentManager = getSupportFragmentManager(); | |
actionBar = getSupportActionBar(); | |
if (actionBar != null) { | |
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); | |
actionBar.setCustomView(R.layout.action_bar_kudolife); | |
header = (MulticoloreTextView) findViewById(R.id.title); | |
} | |
public void nextFragment(Fragment fragment, String newTag, String curTag) { | |
lastFragment = curTag; //Tracks back location | |
Fragment check = checkForFragment(newTag); | |
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); | |
if (check != null) { | |
fragment = check; //Fragment exists | |
} else { | |
fragmentTransaction.addToBackStack(newTag); //Fragment doesn't exist | |
} | |
fragmentTransaction.replace(R.id.parent, fragment, newTag); | |
fragmentTransaction.commit(); | |
} | |
@Override | |
public void onBackPressed() { | |
int i = fragmentManager.getBackStackEntryCount() - 1; | |
for (int j = i; j >= 0; j--) { | |
FragmentManager.BackStackEntry entry = fragmentManager.getBackStackEntryAt(j); | |
String tag = entry.getName(); | |
if (lastFragment.equals(tag)) { | |
Fragment fragment = fragmentManager.findFragmentByTag(tag); | |
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); | |
fragmentTransaction.replace(R.id.parent, fragment, tag); | |
fragmentTransaction.commit(); | |
if (j != 0) { | |
entry = fragmentManager.getBackStackEntryAt(j - 1); | |
lastFragment = entry.getName(); | |
} else { | |
lastFragment = "END OF STACK, NOTHING TO RETURN"; | |
} | |
return; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment