Search code examples
androidxamarin.androidfragmentmanager

Android Xamarin: FragmentManager.FindFragmentByTag is null


I am trying to understand the FragmentMananger better.

I "inflate" my fragment in a FrameLayout, what works fine.

var fragmentTag = typeof(MyFragment).Name;
myFragment = new MyFragment();
FragmentManager.BeginTransaction()
               .Add(Resource.Id.FrameLayout, myFragment, fragmentTag)
               .Commit();

But now the question is, at what moment can i find my fragment via the TagSearch. Because after the BeginTransaction()

FragmentManager.FindFragmentByTag<MyFragment>(typeof(MyFragment).Name

is still null


Solution

  • You can use executePendingTransactions method after Commit method, it will execute immediately.

    And you can also refer to this case.

    Here is the demo based on your last case. I have add some codes in the project:

    FragmentTransaction fragmentTransaction = FragmentManager.BeginTransaction();
    Fragment1 fragment = (Fragment1)FragmentManager.FindFragmentByTag(FRAGMENT_TAG);
    if (fragment == null)
    {
        fragment = new Fragment1();
        fragmentTransaction.Add(fragment, FRAGMENT_TAG).Commit();
        FragmentManager.ExecutePendingTransactions();
    }
    
    Fragment1 f=FragmentManager.FindFragmentByTag<Fragment1>(typeof(Fragment1).Name);
    if (f != null)
    {
        Toast.MakeText(this, "Fragment1 is not null", ToastLength.Short).Show();
    }
    else
    {
        Toast.MakeText(this, "Fragment1 is  null", ToastLength.Short).Show();
    }