Android: How to get the real screen size of the device?

前端 未结 4 1115
温柔的废话
温柔的废话 2021-02-05 18:11

I have tried different ways to get the screen size of the device, but it always returned me the wrong size (791x480 instead of 854x480). It might be du

相关标签:
4条回答
  • 2021-02-05 18:39

    Try calling

        display.getRealSize();
    

    DISCLAIMER: I did not realize this, but this will only work for API 17 (Android 4.2/JellyBean) and up.

    0 讨论(0)
  • 2021-02-05 18:47

    I was facing the same problem on an Android 3.2 tablet. I tested both getRealSize and getDisplayMetrics. They are expected to crash as they meant to be available on API 17. But strangely getDisplayMetrics doesn't crash on my 3.2 and returns the correct dimension. getRealSize crashes.

    0 讨论(0)
  • 2021-02-05 18:48

    if you want to get the size in the activity, you can make it by the following code.

    findViewById(android.R.id.content).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                View view =  findViewById(android.R.id.content);
                Log.e("test", "root view height is " + view.getHeight());
    
            }
        });
    
    0 讨论(0)
  • 2021-02-05 18:58

    Try this

     final DisplayMetrics metrics = new DisplayMetrics(); 
        Display display = getWindowManager().getDefaultDisplay();     
        Method mGetRawH = null,mGetRawW = null;
    
    try {
    
        // For JellyBeans and onward
        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN){
    
            display.getRealMetrics(metrics);
            realWidth = metrics.widthPixels;
            realHeight = metrics.heightPixels;
        }
        else{
        // Below Jellybeans you can use reflection method 
    
            mGetRawH = Display.class.getMethod("getRawHeight");
            mGetRawW = Display.class.getMethod("getRawWidth");
    
            try {
                realWidth = (Integer) mGetRawW.invoke(display);
                realHeight = (Integer) mGetRawH.invoke(display);
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    0 讨论(0)
提交回复
热议问题