Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Orientation and screen size issue

I want to know if the device screen width is larger than height like HTC chacha that its screen's width is 480 and the height is 320

I used this code to determine it

Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        if(display.getWidth() > display.getHeight())
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        else
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

the device actual screen size is 480w x 320h when I use this code I got 320w x 480h

like image 757
MBH Avatar asked Dec 27 '22 03:12

MBH


1 Answers

This code will return width (w) & height (h) of screen.

DisplayMetrics dMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
float density = dMetrics.density;
int w = Math.round(dMetrics.widthPixels / density);
int h = Math.round(dMetrics.heightPixels / density);

activity is instance of Activity which would you like to get screen size.

You have to remember that: When your device is in landscape orientation, w > h. When it in portrait orientation w < h.

So from width & height you can detect your device is in what orientation.

like image 173
Luc Avatar answered Jan 05 '23 06:01

Luc