getMeidth()和getHeight在onMeasure()之后返回零(特定设备)

时间:2013-09-04 03:59:55

标签: android surfaceview viewlayout

我注意到,在调用onMeasure()之后,我的应用程序视图为getWidth()和getHeight()返回0。这只发生在少数设备上,对于大多数Android设备,下面的代码工作正常。我的checkViewAndLoad()函数根据视图的大小加载缩放的位图。

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

以下是onMeasure()之后为getWidth()/ getHeight()返回零的设备(Motorola Droid Razr Maxx)的日志:

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

我也尝试手动设置MeMeuredDimensions(),但是这一手不会影响日志。

有人可以告诉我这里我做错了什么,或者在调用onMeasure()之后如何获得SurfaceView的宽度/高度?

2 个答案:

答案 0 :(得分:9)

在此处使用getMeasuredWidth/Height()getWidth/Height()在布局后才有效。

答案 1 :(得分:1)

尝试这种方式

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

}