I have a ListFragment in my MainActivity. Here is how I set my fragment object.
FragmentManager fragmentManager = activity.getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); Fragment newFragment = new MyFragment(); fragmentTransaction.replace(R.id.framecontainer, newFragment, "tag"); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit();
The problem is when the user press back button, I have to, at least, change the action bar and menu by calling
getActionBar().setTitle(title); getActionBar().setDisplayHomeAsUpEnabled(isEnabled); invalidateOptionsMenu();
I have to know what kind of fragment is showing currently, so that I know how to set the action bar. I store the setting option in fragment as arguments.
String title = fragment.getArguments().getString("KEY_TITLE"); boolean isEnabled = fragment.getArguments().getBoolean("KEY_ISENABLED");
I do search the related question, and I realized I could get the fragment by calling
MyFragment fragment = (MyFragment) getSupportFragmentManager() .findFragmentByTag("tag");
However, I have to store all the tag in a custom stack, and call pop() everytime when user pressed back button in onBackPressed()
.
So, my question is that is there a way for me to get the current visible fragment from the stack directly?
Note: Please keep in mind that the fragment types are different, not just only MyFragment.
To get the current fragment that's active in your Android Activity class, you need to use the supportFragmentManager object. The supportFragmentManager has findFragmentById() and findFragmentByTag() methods that you can use to get a fragment instance.
FragmentManager is the class responsible for performing actions on your app's fragments, such as adding, removing, or replacing them, and adding them to the back stack.
popBackStackImmediate() will perform the popping commands immediately in the call. The results of which can be verified immediately after the call. It is somewhat slower since all the popping actions are performed within the call.
Some thing like this should help your activity figure this out on backpress:
private Fragment getCurrentFragment(){ FragmentManager fragmentManager = getSupportFragmentManager(); String fragmentTag = fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1).getName(); Fragment currentFragment = fragmentManager.findFragmentByTag(fragmentTag); return currentFragment; } @Override public void onBackPressed() { Fragment fragmentBeforeBackPress = getCurrentFragment(); // Perform the usual back action super.onBackPressed(); Fragment fragmentAfterBackPress = getCurrentFragment(); }
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With