【问题标题】:getheight() px or dpi?getheight() 像素还是 dpi?
【发布时间】:2012-08-08 10:17:27
【问题描述】:

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

final ListView actualListView = mPullRefreshListView.getRefreshableView();

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

                    }
                });

【问题讨论】:

  • getHeight();始终以像素为单位返回高度,请为您检查此解决方案。 stackoverflow.com/questions/3166501/…
  • 只是未来的一个旁注。您需要的可能是dpdip - 它们代表与密度无关的像素dpi每英寸点数,它测量的是屏幕的密度,而不是尺寸。

标签: android dpi


【解决方案1】:

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

  public final int getHeight ()

自:API 级别 1

返回视图的高度。 返回

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

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

将像素转换为 dp:

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

或者如果你想在 px 中使用它。

将 dp 转换为像素:

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

【讨论】:

  • 如果在Fragment中使用,getContext()可以产生NullPointerException,而不是你应该在onCreateView()中获取上下文,像这样Context context = view.getContext();
  • 它仅适用于“xdpi”吗?例如,如果在 mdpi 设备中执行相同的代码会发生什么?
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 你能告诉我 458 px 高度的分辨率(以 dpi 为单位)吗?
    【解决方案4】:

    将 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()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 2012-05-19
      相关资源
      最近更新 更多