ChildFragmentManager java.lang.IllegalStateException:活动已被销毁

时间:2016-07-28 06:06:30

标签: java android android-fragments android-fragmentactivity

我尝试使用getChildFragmentManager()在viewpager中的另一个片段内添加一个片段。我收到了以下错误,

  

java.lang.IllegalStateException:活动已被销毁                                                                    在android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1549)                                                                    在android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:654)                                                                    在android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:625)                                                                    在com.lakeba.gameon.userprofile.UserProfileContainerFragment.replaceFragment(UserProfileContainerFragment.java:72)

我尝试this workaround但仍然遇到同样的错误。

UserProfileContainerFragment.java

public class UserProfileContainerFragment extends CustomFragment {


    private View rootView;
    private Fragment fragment1;

    public UserProfileContainerFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    public static UserProfileContainerFragment newInstance() {
        UserProfileContainerFragment fragment = new UserProfileContainerFragment();
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_user_profile_container, container, false);

        if(savedInstanceState == null) {
            UserProfileFragment userProfileFragment = UserProfileFragment.newInstance();
            getChildFragmentManager().beginTransaction()
                    .replace(R.id.user_profile_container, userProfileFragment)
                    .commitAllowingStateLoss();
        }

        return rootView;
    }

    /*@Override
    public void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
    }*/

    public void replaceFragment(Fragment fragment, boolean addToBackStack){
        fragment1 = fragment;
        if(addToBackStack){
            /*getChildFragmentManager().beginTransaction()
                    .replace(R.id.user_profile_container, fragment)
                    .addToBackStack(null)
                    .commit();*/
            getChildFragmentManager().beginTransaction()
                    .replace(R.id.user_profile_container, fragment)
                    .addToBackStack(null)
                    .commit();
                    //.commitAllowingStateLoss();
        }
        else{
            getChildFragmentManager().beginTransaction()
                    .replace(R.id.user_profile_container, fragment)
                    .commit();
                    //.commitAllowingStateLoss();
        }

    }

    @Override
    public void onDetach() {
        super.onDetach();

        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }
}

HomeMapActivity.java

public class HomeMapActivity extends AppCompatActivity implements UserProfileFragment.OnUserProfileFragmentListener{

    private Toolbar homeToolbar;
    private ViewPager homeViewPager;
    private TabLayout homeTabLayout;
    private UserProfileContainerFragment userProfileContainerFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_map);

        /*homeToolbar = (Toolbar) findViewById(R.id.home_toolbar);
        setSupportActionBar(homeToolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);*/

        homeViewPager = (ViewPager) findViewById(R.id.home_view_pager);

        HomeViewPagerAdapter homeViewPagerAdapter = new HomeViewPagerAdapter(getSupportFragmentManager());
        userProfileContainerFragment = new UserProfileContainerFragment();
        homeViewPagerAdapter.addFragment(new UserProfileContainerFragment(),"Profile");
        homeViewPager.setAdapter(homeViewPagerAdapter);

        homeTabLayout = (TabLayout) findViewById(R.id.home_tabs);
        homeTabLayout.setupWithViewPager(homeViewPager);
        setTabIcons(homeTabLayout);


        homeTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int tabPosition = tab.getPosition();
                tab.setIcon(tabIconsArrayActivated[tabPosition]);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                int tabPosition = tab.getPosition();
                tab.setIcon(tabIconsArray[tabPosition]);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                int tabPosition = tab.getPosition();
                tab.setIcon(tabIconsArrayActivated[tabPosition]);
            }
        });

        homeTabLayout.getTabAt(1).select();
    }

    private void setTabIcons(TabLayout homeTabLayout) {
        homeTabLayout.getTabAt(0).setIcon(tabIconsArray[0]);
        homeTabLayout.getTabAt(1).setIcon(tabIconsArray[1]);
        homeTabLayout.getTabAt(2).setIcon(tabIconsArray[2]);
        homeTabLayout.getTabAt(3).setIcon(tabIconsArray[3]);
    }

    @Override
    public void onUserProfileEditButtonClicked() {
        userProfileContainerFragment.replaceFragment(EditUserProfileFragment.newInstance(),true);
    }

    private class HomeViewPagerAdapter extends FragmentStatePagerAdapter{

        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public HomeViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            //return mFragmentTitleList.get(position);
            return null;
        }

        public void addFragment(Fragment fragment,String title){
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }
    }
}

1 个答案:

答案 0 :(得分:5)

如果你查看o​​nCreate()方法中的代码,你会看到以下几行:

userProfileContainerFragment = new UserProfileContainerFragment();
homeViewPagerAdapter.addFragment(new UserProfileContainerFragment(),"Profile");

首先使用UserProfileContainerFragment的新实例初始化userprofileContainerFragment字段,然后在下面创建一个要在ViewPager中使用的UserProfileContainerFragment的 new 实例(您可以通过放置日志语句轻松地观察到这一点)在UserProfileContainerFragment的构造函数中......您将看到正在创建的两个实例)。稍后在您的代码中,您尝试使用字段 userProfileContainerFragment ,这将导致失败,因为UserProfileContainerFragment的实例根本没有附加到活动(这不是ViewPager使用的片段) )。

您的代码应如下所示,以维护正确的引用,而不是创建分离的片段:

userProfileContainerFragment = new UserProfileContainerFragment();
homeViewPagerAdapter.addFragment(userProfileContainerFragment,"Profile");