I noticed that my application's view returns 0 for getWidth() and getHeight() after onMeasure() has already been called. This only happens on a handful of devices, for most android devices the following code works fine. My checkViewAndLoad() function loads a scaled bitmap depending on the size of the view.
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.d("widthMeasureSpec", Integer.toString(MeasureSpec.getSize(widthMeasureSpec)));
Log.d("heightMeasureSpec", Integer.toString(MeasureSpec.getSize(heightMeasureSpec)));
Log.d("viewWidth", Integer.toString(getWidth()));
Log.d("viewHeight", Integer.toString(getHeight()));
checkViewAndLoad();
}
Here is a log of a device (Motorola Droid Razr Maxx) that returns zero for getWidth()/getHeight() after onMeasure():
09-03 20:55:58.359: D/widthMeasureSpec(29496): 540
09-03 20:55:58.359: D/heightMeasureSpec(29496): 720
09-03 20:55:58.359: D/viewWidth(29496): 0
09-03 20:55:58.359: D/viewHeight(29496): 0
I also tried to setMeasuredDimensions() manually, but that hand no affect on the logs.
Can someone tell me what I'm doing wrong here, or how to get the width/height of a SurfaceView after onMeasure() has been called?
Use getMeasuredWidth/Height()
here. getWidth/Height()
aren't valid until after a layout.
Try This way
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
Log.d("widthMeasureSpec", Integer.toString(MeasureSpec.getSize(widthMeasureSpec)));
Log.d("heightMeasureSpec", Integer.toString(MeasureSpec.getSize(heightMeasureSpec)));
Log.d("viewWidth", Integer.toString(getWidth()));
Log.d("viewHeight", Integer.toString(getHeight()));
if(getMeasuredWidth()!=0 && getMeasuredHeight()!=0){
checkViewAndLoad();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With