【问题标题】:How to get width and height of resized custom view , before it is drawn如何在绘制之前获取调整大小的自定义视图的宽度和高度
【发布时间】:2015-07-21 20:22:43
【问题描述】:

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

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

【问题讨论】:

    标签: java android android-custom-view density-independent-pixel onmeasure


    【解决方案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());
    

    【讨论】:

    • 问题是我无法在自定义视图类之外获取视图的宽度和高度,如果我仍然将这些值存储在自定义视图类的静态变量中,则不能保证我会得到实际大小,因为我不知道 onSizechanged 什么时候会调用。
    • onSizeChanged 在布局上被调用。我在所有自定义视图中都使用了它
    • 在我的特殊情况下,正如我的问题中提到的,我试图在主要活动中获取自定义视图的宽度和高度。并且不会调用大小更改。
    • 您可以从自定义视图中公开一个 API(公共方法),Activity 可以使用它来获取高度宽度......类似 customeView.getHeight() 和 customView.getWidth
    • 我已经完成了所有这些,我得到的总是 0
    【解决方案2】:

    我也遇到了同样的问题。

    这是我的解决方案,我是如何遇到类似问题的。在使用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;
               }
           });
    

    【讨论】:

      猜你喜欢
      • 2011-05-03
      • 2016-08-14
      • 2015-07-16
      • 1970-01-01
      • 2012-03-23
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多