get Status Bar Height via Activity Window - Android android.app

Android examples for android.app:Status Bar

Description

get Status Bar Height via Activity Window

Demo Code

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.Window;

public class Main {

  public static int getStatusBarHeight(Activity activity) {
    Rect rect = new Rect();
    Window win = activity.getWindow();
    win.getDecorView().getWindowVisibleDisplayFrame(rect);
    return (int) convertPixelsToDp(rect.top, activity);
  }/*w  w  w . ja  v  a 2  s. c  o  m*/

  /**
   * This method converts device specific pixels to device independent pixels.
   * 
   * @param px
   *          A value in px (pixels) unit. Which we need to convert into db
   * @param context
   *          Context to get resources and device specific display metrics
   * @return A float value to represent db equivalent to px value
   */
  public static float convertPixelsToDp(float px, Context context) {
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / (metrics.densityDpi / 160f);
    return dp;

  }

}

Related Tutorials