Skip to content Skip to sidebar Skip to footer

Fragment Orientation Change - Better Test Than For Landscape

In 'Landscape' mode I have two FrameLayouts controlled by One Activity and utilizing two Fragments. In 'Portrait' mode I have one FrameLayout controlled by One Activity, on Select

Solution 1:

or create a custom resource with a bool value (from google io 2012)

<!-- in your values/custom.xml -->
<resources>
    <bool name="small_screen">true</bool>  
    <bool name="normal_screen">false</bool>  
</resources>

<!-- in your values-sw320dp/custom.xml -->
<resources>
    <bool name="small_screen">false</bool>  
    <bool name="normal_screen">true</bool>
</resources>

NOTE: You have to define a minimum screenwidth (sw320dp) for which you will consider a screen not to be small (link with more info)

The advantage is that you can read this value at runtime & you can have special cases for special resource qualifiers... E.g. you can read this value at runtime by calling in your activity:

if(getResources().getBoolean(R.bool.small_screen)) {
    // You have a screen which is < 320dp
} else {
    // You have a screen which is >= 320dp
}

You can even use this boolean resource in your manifest like so, to start a completely different activity for small screens

<activity android:name="SmallScreenActivity" 
          android:enabled="@bool/small_screen">  <!-- ENABLE FOR SMALL SCREEN -->
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<activity android:name="NormalActivity" 
          android:enabled="@bool/normal_screen"> <!-- ENABLE FOR OTHER -->
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

This way you can simply use an Activity for the normal case (android:enabled="@bool/normal_screen") and use a special activity for small screen android:enabled="@bool/small_screen"

WARNING: This method will not work on newer devices since honeycomb. You can read why this method is not allowed anymore or read about working similar solution


Solution 2:

Preform an additional check for screen size before your check for the orientation. Considering that a small device has a width of 500 pixels and a height of 600 pixels, you would do something like this.

Display display = getWindowManager().getDefaultDisplay(); 
Point size = new Point(); 
display.getSize(size); i
int width = size.x; 
int height = size.y;
if ( width > 500 && height > 600 && 
    getResources().getConfiguration().orientation == 
    Configuration.ORIENTATION_LANDSCAPE)
{ 
     finish(); 
     return; 
}

Post a Comment for "Fragment Orientation Change - Better Test Than For Landscape"