Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Fragment created twice orientation change

My fragment is being created twice, even though the activity is only adding the fragment once to the content. This happens when I rotate the screen. Also, everytime the fragment's onCreateView is called, it has lost all of it's variable state.

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) { // Checking for recreation
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new AppPanelFragment())
                    .commit();
        }
    }

}

onCreate in the activity checks for the null savedInstanceState and only if null will add the fragment so I can't see why the fragment should be created twice? Putting a breakpoint in that if condition tells me that it only ever get's called once so the activity shouldn't be adding the fragment multiple times. However the onCreateView of the fragment still gets called each time orientation changes.

        public class AppPanelFragment extends Fragment {

            private TextView appNameText;

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
// This method called several times
                View rootView = inflater.inflate(R.layout.fragment_app_panel, container, false);

// 2nd call on this method, appNameText is null, why?
appNameText = (TextView) rootView.findViewById(R.id.app_name);
appNameText.text = "My new App";

    return view;

    }

I managed to have the variable state persisted using setRetainInstance(true), but is this the real solution? I would expect the fragment to not be created on just an orientation change.

like image 974
monokh Avatar asked Mar 21 '15 00:03

monokh


1 Answers

In android, when the phone's orientation is changed, the activity is destroyed and recreated. Now, i believe to fix your problem you can use the fragment manager to check to see if the fragment already exists in the back stack and if it doesn't then create it.

public void onCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            mFragmentManager = getSupportFragmentManager();
            AppPanelFragment fragment  = (AppPanelFragment)mFragmentManager.findFragmentById(R.id.fagment_id);
            if(fragment == null) {
                //do your fragment creation
            } 
        }
    }

P.S. I haven't tested this but it should work once you provide the right fragment's id in the findFragmentById method.

like image 60
The Code Pimp Avatar answered Nov 03 '22 00:11

The Code Pimp