ViewPager and fragments — what's the right way to store fragment's state?

后端 未结 11 1340
遇见更好的自我
遇见更好的自我 2020-11-22 02:21

Fragments seem to be very nice for separation of UI logic into some modules. But along with ViewPager its lifecycle is still misty to me. So Guru thoughts are b

11条回答
  •  遇见更好的自我
    2020-11-22 02:36

    I found another relatively easy solution for your question.

    As you can see from the FragmentPagerAdapter source code, the fragments managed by FragmentPagerAdapter store in the FragmentManager under the tag generated using:

    String tag="android:switcher:" + viewId + ":" + index;
    

    The viewId is the container.getId(), the container is your ViewPager instance. The index is the position of the fragment. Hence you can save the object id to the outState:

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("viewpagerid" , mViewPager.getId() );
    }
    
    @Override
        protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        if (savedInstanceState != null)
            viewpagerid=savedInstanceState.getInt("viewpagerid", -1 );  
    
        MyFragmentPagerAdapter titleAdapter = new MyFragmentPagerAdapter (getSupportFragmentManager() , this);        
        mViewPager = (ViewPager) findViewById(R.id.pager);
        if (viewpagerid != -1 ){
            mViewPager.setId(viewpagerid);
        }else{
            viewpagerid=mViewPager.getId();
        }
        mViewPager.setAdapter(titleAdapter);
    

    If you want to communicate with this fragment, you can get if from FragmentManager, such as:

    getSupportFragmentManager().findFragmentByTag("android:switcher:" + viewpagerid + ":0")
    

提交回复
热议问题