Get the screen height in Android

前端 未结 9 1184
忘了有多久
忘了有多久 2021-02-05 09:57

How can I get the available height of the screen in Android? I need to the height minus the status bar / menu bar or any other decorations that might be on screen and I need it

9条回答
  •  深忆病人
    2021-02-05 10:08

    Working solution:

    Create two dummy views :

     
    
    
    

    Now, you should call getLocationOnScreen(int []) on these two views to receive their locations. This function returns an array of 2 integers. The first being x and the second y. We require only y. Also note that correct values are returned only AFTER all the views are created and the onCreate method is exited.

    I tested this code on a regular fragment called from a viewpager.

    The code was in the onCreateView method of my fragment. I still had to use a postDelayed to get the correct values.

    final View top = (View) view.findViewById(R.id.top);
        final View bottom = (View) view.findViewById(R.id.bottom);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
    
                int topLoc[] = new int[2];
                top.getLocationOnScreen(topLoc);
                int BottomLoc[] = new int[2];
                bottom.getLocationOnScreen(BottomLoc);
                Log.d(Constants.debug, "topY: "+ topLoc[1]+" BottomY:" + BottomLoc[1]);
            }
        },4000);
    

    I have a Nexus 4.

    In regular mode (status bar and the soft buttons shown) :

    07-05 02:28:23.367      565-565/com.torcellite.xx D/xx: topY: 50 BottomY:1182
    

    In full screen mode (no status bar or soft buttons shown) :

    07-05 02:29:17.360      707-707/com.torcellite.xx D/xx: topY: 0 BottomY:1280
    

    All you have to do now is subtract.

提交回复
热议问题