Search code examples
androidandroid-layoutlandscape-portraitportrait

Portrait mode for Phones and Portrait+Landscape for Tablets


I am building a universal android app, where phones need to support only portrait and tablets will support both portrait and landscape. Here is my layout structure

layout-port layout-sw600dp-port layout-sw600dp-land

But if the phone is in landscape mode, the app crashes, reasoning Resource not found Exception.


Solution

  • This way should work:Define boolean value inside values-sw600dp boolean.xml file.

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <bool name="tablet">true</bool>
    </resources>
    

    Define similar file inside the regular values folder and chnage the value to false:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <bool name="tablet">false</bool>
    </resources>
    

    Put this in your onCreate:

    boolean tablet = getResources().getBoolean(R.bool.tablet);
    if (!tablet) 
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);