问题
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