getheight() px or dpi?

Max Usanin picture Max Usanin · Aug 8, 2012 · Viewed 22.4k times · Source

Help.I found the height of ListView and I do not know px or dpi? I need dpi

final ListView actualListView = mPullRefreshListView.getRefreshableView();

actualListView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    public void onGlobalLayout() {
                        height = actualListView.getHeight();  

                    }
                });

Answer

AAnkit picture AAnkit · Aug 8, 2012

getheight return height in pixels, Below is what docs says..

  public final int getHeight ()

Since: API Level 1

Return the height of your view. Returns

The height of your view, in pixels.

You need to convert px into dp , use below ways to convert it to dp.

Convert pixel to dp:

public int pxToDp(int px) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
    return dp;
}

or if you want it in px use below.

Convert dp to pixel:

public int dpToPx(int dp) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
    return px;
}