如何获得宽度和调整自定义视图的高度,它绘制之前 [英] How to get width and height of resized custom view , before it is drawn

查看:163
本文介绍了如何获得宽度和调整自定义视图的高度,它绘制之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的自定义视图的.xml,我已经定义的宽度和高度为 W = 600dp的,H = 700dp 。现在我知道视图绘制后getMeasuredHeight()/ getMeasuredWidth()给予的宽度和高度的价值,他们可以从我的.xml文件中已经给什么不同,有一种解决方法获得 getMeasuredHeight() getMeasuredWidth()视图前值实际上是借鉴了布局,不使用 onMeasure的()

In my custom View .xml , i have defined width and height as w = 600dp , h = 700dp. Now i know getMeasuredHeight() / getMeasuredWidth() give values of width and height after view is drawn and they may differ from what i've given in .xml file , is there a workaround to get getMeasuredHeight() and getMeasuredWidth() values before view is actually drawn on layout, without use of onMeasure() ?

以及如何计算改变 DP 尺寸在不同的屏幕?就像我的 600H *700瓦特当模拟器运行转换为 300 * 300

And How to calculate changed dp sizes in different screens ? like my 600h*700w when run on emulator converts to 300*300 .

推荐答案

您可以覆盖 onSizeChanged()来获取视图的高度和宽度当它是drawn.refer如下:

You can override onSizeChanged() to get height and width of the view when it is drawn.refer below:

  @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转换成可以使用以下code像素:

To convert dp into pixels you can use following code:

   sizeInPixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            sizeInDp, getResources().getDisplayMetrics());

这篇关于如何获得宽度和调整自定义视图的高度,它绘制之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆