Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getWidth() and getHeight return zero after onMeasure() (specific devices)

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?

like image 874
dsmflyer Avatar asked Sep 04 '13 03:09

dsmflyer


2 Answers

Use getMeasuredWidth/Height() here. getWidth/Height() aren't valid until after a layout.

like image 52
alex Avatar answered Nov 06 '22 15:11

alex


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

}
like image 1
Biraj Zalavadia Avatar answered Nov 06 '22 16:11

Biraj Zalavadia