0

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

ColdFire
  • 6,764
  • 6
  • 35
  • 51
Aiko West
  • 791
  • 1
  • 10
  • 30

2 Answers2

1

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();
}
Robbit
  • 4,300
  • 1
  • 13
  • 29
0

Try change tag something static. Like this.

myFragment = new MyFragment();
FragmentManager.BeginTransaction()
               .Add(Resource.Id.FrameLayout, myFragment, "MyFragmentTag")
               .Commit();

FragmentManager.FindFragmentByTag<MyFragment>("MyFragmentTag");
Maxitors
  • 236
  • 2
  • 8