Fragments Not Working Correctly After Orientation Change

后端 未结 5 1256
失恋的感觉
失恋的感觉 2020-12-14 10:36

I am having a problem with Fragments and orientation change.

I have an application which has a MainActivity which handles the switching up

5条回答
  •  庸人自扰
    2020-12-14 11:26

    It sounds like you don't have something in your onCreate method wrapped in a if(savedInstanceState == null), so you are creating another fragment in addition to the one being restored from the savedInstanceState bundle.

    EDIT

    Looking more closely at your code, I think I was wrong about the onCreate, your onTabSelected should handle it. I think your if (mFragment == null) is always coming up null, because you don't try and find the fragment. Change that code section to:

    @Override 
    public void onTabSelected(Tab tab, android.support.v4.app.FragmentTransaction ft) { 
    
        mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag);   // add this
    
        if (mFragment == null){ // check to see if the fragment has already been initialised. If not create a new one. 
            mFragment = android.support.v4.app.Fragment.instantiate(mActivity, mClass.getName()); 
            ft.add(android.R.id.content,mFragment,mTag); 
        } else { 
            ft.attach(mFragment); // if the fragment has been initialised attach it to the current activity 
        } 
    } 
    

提交回复
热议问题