Android getheight() px 还是 dpi?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11862391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:02:37  来源:igfitidea点击:

getheight() px or dpi?

androiddpi

提问by Max Usanin

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

求助,我找到了ListView的高度,不知道是px还是dpi?我需要 dpi

final ListView actualListView = mPullRefreshListView.getRefreshableView();

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

                    }
                });

回答by AAnkit

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

getheight 以像素为单位返回高度,下面是文档所说的..

  public final int getHeight ()

Since: API Level 1

Return the height of your view. Returns

The height of your view, in pixels.

从:API 级别 1

返回视图的高度。退货

视图的高度,以像素为单位。

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

您需要将 px 转换为 dp ,使用以下方法将其转换为 dp。

Convert pixel to dp:

将像素转换为 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.

或者如果你想在 px 中使用它,请在下面使用。

Convert dp to pixel:

将 dp 转换为像素:

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

回答by barisemreefe

It returns pixels. http://developer.android.com/reference/android/view/View.html#getHeight()To convert pixels to dpi use this formula px = dp * (dpi / 160)

它返回像素。 http://developer.android.com/reference/android/view/View.html#getHeight()将像素转换为 dpi 使用此公式 px = dp * (dpi / 160)

回答by Parag Chauhan

Using this code you can get runtime Display's Width & Height

使用此代码,您可以获得运行时显示的宽度和高度

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int wwidth = displaymetrics.widthPixels;

回答by mmBs

The functions for converting dp to px and px to dp should look like below (in kotlin):

将 dp 转换为 px 和将 px 转换为 dp 的函数应如下所示(在 kotlin 中):

fun convertDpToPx(dp: Int): Int {
    val metrics = Resources.getSystem().displayMetrics
    return dp * (metrics.densityDpi / 160f).roundToInt()
  }

fun convertPxToDp(px: Int): Int {
  val metrics = Resources.getSystem().displayMetrics
  return (px / (metrics.densityDpi / 160f)).roundToInt()
}