Getting the error “Java.lang.IllegalStateException Activity has been destroyed” when using tabs with ViewPager

前端 未结 13 2189
再見小時候
再見小時候 2020-11-22 11:53

I have an application that consists of using ActionBarSherlock in tab mode.I have 5 tabs and the content of each tab is handled using fragments. For tab2 though, I have a fr

13条回答
  •  自闭症患者
    2020-11-22 12:34

    This one drove me crazy for Xamarin.

    I ran into this with a ViewPager implementation for TabLayout WITHIN a Fragment, that is itself implemented in the DrawerLayout:

     - DrawerLayout
       - DrawerFragment
         - TabLayout
         - TabViewPager
           - TabViewPagerFragments
    

    So you have to implement the following code in your DrawerFragment. Be aware to choose the correct FragmentManager-Path. Because you might have two different FragmentManager References:

    1. Android.Support.V4.App.FragmentManager
    2. Android.App.FragmentManager

    --> Choose the one you use. If you want to make use of the ChildFragmentManager, you had to use the class declaration Android.App.FragmentManager for your ViewPager!

    Android.Support.V4.App.FragmentManager

    Implement the following Method in your "Main" Fragment - in this example: DrawerFragment

    public override void OnDetach() {
        base.OnDetach();
        try {
            Fragment x = this;
            var classRefProp = typeof(Fragment).GetProperty("class_ref", BindingFlags.NonPublic | BindingFlags.Static);
            IntPtr classRef = (IntPtr)classRefProp.GetValue(x);
            var field = JNIEnv.GetFieldID(classRef, "mChildFragmentManager", "Landroid/support/v4/app/FragmentManagerImpl;");
            JNIEnv.SetField(base.Handle, field, IntPtr.Zero);
        }
        catch (Exception e) {
            Log.Debug("Error", e+"");
        }
    }
    

    Android.App.FragmentManager

    public class TabViewPager: Android.Support.V13.App.FragmentPagerAdapter {}
    

    That means you had to init the ViewPager with Android.App.FragmentManager.

    Implement the following Method in your "Main" Fragment - in this example: DrawerFragment

    public override void OnDetach() {
        base.OnDetach();
        try {
            Fragment x = this;
            var classRefProp = typeof(Fragment).GetProperty("class_ref", BindingFlags.NonPublic | BindingFlags.Static);
            IntPtr classRef = (IntPtr)classRefProp.GetValue(x);
            var field = JNIEnv.GetFieldID(classRef, "mChildFragmentManager", "Landroid/app/FragmentManagerImpl;");
            JNIEnv.SetField(base.Handle, field, IntPtr.Zero);
        }
        catch (Exception e) {
            Log.Debug("Error", e+"");
        }
    }
    

提交回复
热议问题