Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

android - How to get real screen height and width?

DisplayMetrics metrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenWidth = metrics.widthPixels;
screenHeight = metrics.heightPixels;

I use these codes to get the height and width of screen

the screen height on my Nexus7 should be 1280

but it return 1205...

and my minSdkVersion is level 8

so i can't use these method:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screen_width = size.x;
int screen_height = size.y;

now, how should i get the correct screen size ?

Edit:

if (Build.VERSION.SDK_INT >= 11) {
        Point size = new Point();
        try {
            this.getWindowManager().getDefaultDisplay().getRealSize(size);
            screenWidth = size.x;
            screenHeight = size.y;
        } catch (NoSuchMethodError e) {
            Log.i("error", "it can't work");
        }

    } else {
        DisplayMetrics metrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;
    }

use it works!

question from:https://stackoverflow.com/questions/14341041/how-to-get-real-screen-height-and-width

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think this will work. The trick is you must use:

display.getRealSize(size);

not

display.getSize(size);

To deal with your API 8 coding issue do something like this:

try { 
    display.getRealSize(size);
    height = size.y; 
} catch (NoSuchMethodError e) {
    height = display.getHeight();
}

Only more recent API devices will have onscreen navigation buttons and thus need the new method, older devices will throw an exception but will not have onscreen navigation thus the older method is fine.

In case it needs to be said: Just because you have a minimumAPI level of 8 for your project doesn't mean you have to compile it at that level. I also use level 8 for minimum but my project mostly are compiled at level 13 (3.2) giving them access to a lot of new methods.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...