UserProfileContainerFragment

UserProfileContainerFragment

我试图使用getChildFragmentManager()在viewpager的另一个片段内添加一个片段。我出现以下错误,



我尝试了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);
        }
    }
}

最佳答案

如果您查看onCreate()方法中的代码,则会看到以下几行:

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

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

您的代码应如下所示,以维护正确的引用并且不创建分离的片段:
userProfileContainerFragment = new UserProfileContainerFragment();
homeViewPagerAdapter.addFragment(userProfileContainerFragment,"Profile");

08-18 11:24