birraa birraa - 1 year ago 87
Android Question

Changing layout orientation only for large devices

An android application I am working on needs to change screen layout only when the screen size is above 7''. I created different layouts for large and xlarge for both land and portrait modes. This seems to have worked well.

I used the following code to determine screen size and change layout accordingly:

public void onConfigurationChanged(Configuration newConfig) {
DisplayMetrics dm = new DisplayMetrics();

int width = dm.widthPixels, height = dm.heightPixels;
double dd = Math.sqrt(width * width + height * height)/dm.densityDpi;
double diagonal = (dd >= (Math.floor(dd) + 0.5) ? Math.ceil(dd) : Math.floor(dd));

if (diagonal < 7) {

The problem:

The layout for screens below 7'' is also changed to landscape mode. The above code could not stop the change. Keep in mind that the layout for below 7'' is also created.

What am I doing wrong here?

Answer Source

There are Two factors here, the first one is your layouts folders and the second one is your code, when you want to represent different layouts for different screens you should use layout, layout-sw600dp, and layout-sw720dp. In this case the layouts in the folder layout is the layouts for the device which is below 7in and thelayout-sw600dp' represent the layouts for devices with minimum size of 7'in and the folder layout-720dp' represents the layouts for the devices bigger that 7in and till the 10`in devices.

The second factor is applying orientation to these layouts, this can happen easily in your onCreate() method using Configuration.class:

    Configuration conf = getResources().getConfiguration();
    if (conf.smallestScreenWidthDp >= 600) { // now it is at least a tablet with 7'in
        if (conf.smallestScreenWidthDp >= 720) { // now it is a 10'in tablet
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); // Or portrait
        } else { // now it is a 7'in tablet
    } else { // now it is a regular device below 7`in
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download