getWidth() and getHeight return zero after onMeasu

2019-04-28 13:05发布

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?

2条回答
在下西门庆
2楼-- · 2019-04-28 13:42

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

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-04-28 13:50

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

}
查看更多
登录 后发表回答