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

I noticed that my application view returns 0 for getWidth () and getHeight () after onMeasure () has already been called. This only happens on a few devices, for most Android devices this code works fine. My checkViewAndLoad () function loads a scaled bitmap based 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 the device log (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 set MeasuredDimensions () manually, but this hand does not affect the logs.

Can someone tell me what I'm doing wrong here, or how to get the width / height of a SurfaceView after calling onMeasure ()?

+6
source share
2 answers

Use getMeasuredWidth/Height() here. getWidth/Height() invalid only after layout.

+9
source

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

Source: https://habr.com/ru/post/953118/


All Articles