Handle Orientation change in Android

Shweta

To support landscape and portrait orientation in Android you need to override SaveInstanceState for Activity as well as Fragment. In activity’s onCreate method check whether activity has savedInstance or not. If yes then do not add/replace the fragment. If you will add/replace, then the fragment will get created twice. Similarly check for SavedInstance for fragment’s onCreate or onCreateView callback.
eg. DetailActivity has DetailFragment. Below are the code for DetailActivity and DetailFragment.

 

public class DetailActivity extends AppCompatActivity {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_detail);
              Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
              setSupportActionBar(toolbar);
              getSupportActionBar().setDisplayHomeAsUpEnabled(true);

              if (savedInstanceState == null) {
                        DetailFragment detailFragment = new DetailFragment();
                        detailFragment.setArguments(getIntent().getExtras());

                        // need to check for savedInstanceState
                        getSupportFragmentManager().beginTransaction().replace(R.id.container, detailFragment).commit();
              }
        }

        @Override
        protected void onSaveInstanceState(Bundle outState) {
              super.onSaveInstanceState(outState);
              outState.putBoolean(AppConstants.SAVE_ACTIVITY_STATE, true);
        }
}

public class DetailMovieFragment extends Fragment{

         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
         Bundle savedInstanceState) {
                 View view = inflater.inflate(R.layout.fragment_detail_movie, container, false);
                 if (savedInstanceState != null) {
                          // TODO: check the saved state
                 }
         return view;
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
                super.onSaveInstanceState(outState);
                outState.putBoolean(AppConstants.SAVE_FRAGMENT_STATE, true);
         }
}

 

With this you don’t need to mention anything in AndroidManifest file, if you have configChanges in Manifest please remove it. This is how you handle orientation change in Android.┬áTechJini is a leading mobile app design company and specializes in making iPhone Apps and Android Apps.

about the author

Shweta