Simplest and most difficult-how to get the height of the Android Control
Problem
How to get the length and height of a control? I believe many of my friends will think it is very easy to see this problem at first glance. Just call getWidth and getMeasuredWidth in onCreate to get it. However, in fact, it is not simple. If you don't believe it, you can try it. In onCreate, you cannot obtain the length and width, which is always 0.
Cause
This is why. In fact, our friends who are familiar with the view rendering process should be able to see it at a Glance. In onCreate, our controls are not actually well painted yet. In other words, when the onCreate method is completed, the control we define will be measured, so we use the view in the onCreate method. getHeight (): The height or width of the control must be 0.
Solution
No1:
int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);imageView.measure(w, h);int height = imageView.getMeasuredHeight();int width = imageView.getMeasuredWidth();
This method is very simple, that is, we can measure it ourselves.
No2:
ViewTreeObserver vto = imageView.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { vto.removeOnPreDrawListener(this); int height = imageView.getMeasuredHeight(); int width = imageView.getMeasuredWidth(); return true; } });
In this method, we need to register a listener callback for ViewTreeObserver. This listener callback is used to listen for plotting. Since it is used to listen for plotting, We can naturally obtain the measured value. At the same time, we remove the previous listener before each listener to avoid repeated listeners.
No3:
ViewTreeObserver vto = imageView.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this); imageView.getHeight(); imageView.getWidth(); } });
This method is basically the same as the 2nd method, but it is the global layout change listener, so it is the most recommended.
Okay. Now, it seems that simple problems are not that simple.
Above.