In my application i have one main activity and several fragments. when user click the back button fragments pops one by one. I want to identify which fragment currently in the back stack. So use to identify fragments by fragment tag name. i used following code segment to get fragment tag name but it always returns null value.
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
String fragmentTag = fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName();
please help.
Edit,
replacing fragment with tag,
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.activity_main_content_fragment, fragment, text);
You need to mention the TAG while adding/ replacing it:
ft.replace(R.id.container, newFragment,"fragment_tag_String");
OR
ft.add(R.id.container, newFragment,"fragment_tag_String");
Add the fragment in BackStack as :
ft.addToBackStack("fragment_tag_String");
Then you can reuse it with
getSupportFragmentManager().findFragmentByTag("fragment_tag_String");
Refer :
Call getSupportFragmentManager().executePendingTransactions()
after doing the transaction
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.activity_main_content_fragment, fragment, text);
ft.commit();
fm.executePendingTransactions();
Hope it will help you ツ
i found my mistake, it is i forgot to add TAG to back stack.
FragmentManager fm = mainActivity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.activity_main_content_fragment, fragment, text);
ft.addToBackStack(text);
And then i can get the current fragment TAG name as follows,
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
String currentFragmentTag = fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName();
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