Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findFragmentByTag() always return null - Android

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);
like image 233
user3800832 Avatar asked Nov 18 '14 07:11

user3800832


2 Answers

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 :

  • Replace fragment with TAG
  • Add fragment with TAG

Edit :

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 ツ

like image 145
SweetWisher ツ Avatar answered Nov 15 '22 20:11

SweetWisher ツ


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();
like image 31
user3800832 Avatar answered Nov 15 '22 18:11

user3800832