How to get real screen height and width?

前端 未结 3 847
攒了一身酷
攒了一身酷 2020-12-04 15:51
DisplayMetrics metrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenWidth = metrics.widthPixels;
screenHeight = met         


        
3条回答
  •  不知归路
    2020-12-04 16:16

    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.

提交回复
热议问题