FindFragmentByTag () always returns null - Android

In my application, I have one main action and several fragments. when the user clicks the buttons back, the fragments appear one at a time. I want to determine which fragment is in the background stack. Therefore, use to identify fragments by the name of the fragment tag. I used the following code segment to get the fragment tag name, but it always returns a null value.

FragmentManager fm = MainActivity.this.getSupportFragmentManager(); String fragmentTag = fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName(); 

Please, help.

Edit

replace the fragment with a tag,

 FragmentManager fm = MainActivity.this.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.activity_main_content_fragment, fragment, text); 
+6
source share
2 answers

I found my mistake, I forgot to add TAG to the 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 name of the TAG fragment as follows,

 FragmentManager fm = MainActivity.this.getSupportFragmentManager(); String currentFragmentTag = fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName(); 
+9
source

You must specify the TAG when adding / replacing:

 ft.replace(R.id.container, newFragment,"fragment_tag_String"); 

OR

 ft.add(R.id.container, newFragment,"fragment_tag_String"); 

Add the snippet to BackStack as:

 ft.addToBackStack("fragment_tag_String"); 

Then you can reuse it with

 getSupportFragmentManager().findFragmentByTag("fragment_tag_String"); 

Contact:

Edit:

Call getSupportFragmentManager().executePendingTransactions() after 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 this helps you.

+13
source

Source: https://habr.com/ru/post/978316/


All Articles