get Status Bar Height and return device independent pixels - Android Hardware

Android examples for Hardware:Device Feature

Description

get Status Bar Height and return device independent pixels

Demo Code


//package com.java2s;

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);
    }// ww  w .j a  v  a2s  .  co 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