Wednesday 22 June 2016

Android Handling Configuration Change to Update the Layouts for Different Orientation

There are generally two used methods to provide different layout for different orientation
First is to,

  1. Override the onConfigurationChanged() method and add setContentView(R.layout.layoutname) only if you have edited the manifest file and have added android:configChanges="orientation|screenSize" or android:configChanges="orientation" together with the android:name attribute of activity.
  2. If not then you can perform action to change layout in onCreate() method replacing setContentView(R.layout.layoutname);
  3. The technique is to find the current orientation (Portrait or Landscape) and then set the Content View with the Desired layout ,Example
    if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_LANDSCAPE){
        setContentView(R.layout.landscapeLayout);
    
    }
    else if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_PORTRAIT) {
       setContentView(R.layout.portraitLayout);
    }
  4. Thus load the layout designed for Potrait or Lanscape by including the above code inside either onCreate() or in onConfigurationChanged() method.. IMPORTANT refer 1 and 2 to choose the method either onCreate() or onConfigurationChanged().
  5. IMPORTANT: Make sure that the layout xml file has different name for different orientations example R.layout.landscapeLayout and R.layout.portraitLayout layout names for Landscape and Portrait layout respectively

Second is to,

  1. Create a directory for Landscape and Portrait in the Layout folder inside res folder as
  2.  Create layout-land directory by right clicking on res folder and add paste the xml layout file for Landscape mode inside it, This file will be used in Landscape mode by android itself.
  3. The default path layout is for Portrait mode, and android use the file inside this for Portrait mode.
  4. IMPORTANT: Make sure that the layout xml file has same name in both directories layout-land and layout.
  5. That's all
More at:https://developer.android.com/training/basics/supporting-devices/screens.html

No comments:

Post a Comment