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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-07 03:07:44

问题


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?


回答1:


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




回答2:


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

}


来源:https://stackoverflow.com/questions/18605187/getwidth-and-getheight-return-zero-after-onmeasure-specific-devices

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