How to get width and height of resized custom view , before it is drawn

↘锁芯ラ 提交于 2019-12-13 19:43:11

问题


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() ?

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


回答1:


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);
}

To convert dp into pixels you can use following code:

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


来源:https://stackoverflow.com/questions/31548891/how-to-get-width-and-height-of-resized-custom-view-before-it-is-drawn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!