Home > Tricks & Tips > Detect layout type (landscape/portrait)

Detect layout type (landscape/portrait)


There will be a time you need to define your application GUI both in landscape and portrait (just rotate the phone).

Luckily, every droid has the built-in function to detect layout type. What you need to implement is:

1. Create two main.xml files for layout in both case: landscape and portrait.

2. Put those two main.xml in resources according to its type:

/res/layout-land/main.xml

/res/layout-port/main.xml

Just build and try your application GUI in runtime.

 

In case, you want to detect the timing when layout type change and you want to do some additional works in coding, you might wanna follow these steps:

1. Add android:configChanges=”orientation” to AndroidManifest.xml

2. Detect the orientation change:

@Override
public void onConfigurationChanged(Configuration newConfig) {
      Configuration c = getResources().getConfiguration();

      if(c.orientation == Configuration.ORIENTATION_PORTRAIT ) {
        // portrait

      } else if(c.orientation == Configuration.ORIENTATION_LANDSCAPE ){
        // landscape

      }
}

Hope you enjoy it!

 

Cheers,
Pete Houston

About these ads
  1. Szabi
    June 15, 2012 at 7:46 pm

    Cause’ the changes are in “Configuration newConfig” not in the initial config file.

  2. October 26, 2011 at 9:11 pm

    Not works this tip: 2. Detect the orientation change

    • October 26, 2011 at 10:06 pm

      Do step 1. first then step 2. will work.

      • January 20, 2012 at 12:13 pm

        The “order” that you type the code in… doesn’t make any difference at all.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: