2

在我的自定义 View .xml 中,我将宽度和高度定义为w = 600dp , h = 700dp. 现在我知道 getMeasuredHeight() / getMeasuredWidth() 在绘制视图后给出宽度和高度值,它们可能与我在 .xml 文件中给出的值不同,是否有一种解决方法可以在视图实际绘制在布局上之前getMeasuredHeight()获取值getMeasuredWidth(), 不使用onMeasure()?

以及如何计算dp不同屏幕中更改的尺寸?像我600h*700w在模拟器上运行时转换为300*300.

4

2 回答 2

1

onSizeChanged()您可以在绘制视图时覆盖以获取视图的高度和宽度。请参阅以下内容:

  @Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    mWidth = w;
    mHeight = h;
    super.onSizeChanged(w, h, oldw, oldh);
    Log.d(TAG, "onSizeChanged: " + " width: " + w + " height: " + h + " oldw " + oldw + " oldh " + oldh);
}

要将 dp 转换为像素,您可以使用以下代码:

   sizeInPixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            sizeInDp, getResources().getDisplayMetrics());
于 2015-07-21T20:36:01.857 回答
0

我有同样的问题。

这是我的解决方案,我是如何遇到类似问题的。在那里你可以在绘制图像之前获得宽度和高度OnPreDrawListener()

     ImageView iv= binding.photoRoundProfile;
     ViewTreeObserver vto = iv.getViewTreeObserver();
     vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
   
           private int mFinalWidth = 0;
           private int mFinalHeight = 0;
   
           public boolean onPreDraw() {
   
               if(mFinalHeight != 0 || mFinalWidth != 0)
                   return true;
   
               mFinalHeight = iv.getHeight();
               mFinalWidth = iv.getWidth();
               Log.d("hilength","Height: " + mFinalHeight + " Width: " + mFinalWidth);
   
               ImageUtil.setPic(binding.photoRoundProfile, mCurrentPhotoPath);
               return true;
           }
       });
于 2020-08-26T16:26:26.287 回答