user1156041
user1156041

Reputation: 2195

Android : Fragment onCreateView method call again after orientation changed

I implement the app which has two layout for landscape and portrait mode. The layout for landscape is in the layout-land. I have the fragment1 for portrait layout and fragment2 for landscape layouts. I override the onCreateView in each fragment.

I have static variable to know the current fragment. I assgined in the onCreateView (1 for fragment1 and 2 for fragment2).

My problem is that the static value is still 1 when the orientation is landscape mode.

I debugged the orientation of application. When I change orientation portrait into landscape, fragment2's onCreateView method called first and then the fragment1's onCreateView method called again. The static value has overridden.

I don't know why did fragment1 onCreateView method call after the fragment2 called? I want to assign the right value for right fragment.

Sorry for my bad English.

Thanks.

Upvotes: 3

Views: 2752

Answers (4)

Edward
Edward

Reputation: 49

You don`t need to save something! Just let your activity handle the orientation change. In AndroidManifest.xml put this

    <activity
        android:name=".MainActivity"
        android:configChanges="orientation|screenSize" >
    </activity>

Upvotes: 2

thaussma
thaussma

Reputation: 9886

You should have two special Fragment implementations, if your Fragments have a different 'business logic' in landscape and portrait. If they just have a different layout then use 1 Fragment implementation, and create 2 layouts, one for each orientation.

Instantiate and create your Fragments in Activity.onCreate(). But do not save the current Fragment in a static variable. Instead ask the FragmentManager if a Fragment has already been added:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Fragment myFragment = getSupportFragmentManager().findFragmentByTag("myTag");
    if(myFragment == null){
        //no Fragment has been added
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(new MyFragment1(), "myTag");
        transaction.commit();
    }else{
        //the fragment has been added already, possibley before orientation change
        //you could check its type and replace it
        if(fragment instanceof MyFragment1){

        }else if(fragment instanceof MyFragment2{

        }
    }
}

Upvotes: 0

AndroidHacker
AndroidHacker

Reputation: 3596

Inside the onCreate of each fragment you have to call

getActivity().setRequestedOrientation(requestedOrientation)

Upvotes: 0

Nishanth Kumar
Nishanth Kumar

Reputation: 121

You need to save the bundle and must override onsavedinstance method so that the activityis not createdagain.

First when orientation is changed android checks for the savedinstancestate and calls onSavedInstanceState method if implemented.

Upvotes: 1

Related Questions