Two ways to get the height of the status bar in Android

When making a function about FAB, you need to get the height of the status bar. I checked many methods on the Internet. The following are two more reasonable methods selected. Mainly refer to this question and answer on stackoverflow: http://stackoverflow.com/questions/3407256/height-of-status-bar-in-android

method one:

private double getStatusBarHeight(Context context){
        double statusBarHeight = Math.ceil(25 * context.getResources().getDisplayMetrics().density);
        return statusBarHeight;
    }


This method is very simple, only one line of code, you can translate it after checking the reference manual:

Status bar height = take the smallest integer greater than it (25*context_get the resource instance of the application package_get the current screen size_screen density ratio)

The density is not the real screen density, but a relative density. The benchmark density is 160dpi. For example, the mobile phone I tested is HTC one m8, and the screen density checked is 441dpi, which is 2.75 relative to 160, and density is taken as 3. The density value of each resolution is:

  • ldpi (dpi=120,density=0.75)
  • mdpi (dpi=160,density=1)
  • hdpi (dpi=240,density=1.5)
  • xhdpi (dpi=320,density=2)
  • xxhdpi (dpi=480,density=3)

So the obtained status bar height is 25*3=75

The height of the status bar obtained by this method has great limitations. For example, because the status bar needs to be removed or there is no status bar itself, the height of the status bar should be 0, but this method can still get a non-zero status bar. high.

Method Two:

private int getStatusBarHeight(Context context) {
       int result = 0;
       int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
       if (resourceId > 0) {
           result = context.getResources().getDimensionPixelSize(resourceId);
       }
       return result;
   }

Here we use the getIdentifier() method to get the ID of the resource. The first parameter is to get the name of the resource object. For example, if we want to get the relevant content of the status bar, fill in "status_bar_height" here; the second parameter is What attributes do we want to get, we want to get the height content, so fill in "dimen"; the third is the package name, and the status bar is the system content, so fill in "android".

Another method used is getDimensionPixelSize(). From the function name, you can know that the resource pixel size is obtained according to the resource ID. Here, the height of the status bar is directly obtained.

This method will get its height to 0 when the status bar does not exist.

Guess you like

Origin blog.csdn.net/w_kahn/article/details/50684436