Problem
How to get a control of the length and height, I believe many friends at the first sight of this problem will feel very simple, directly in the OnCreate inside call getwidth, getmeasuredwidth can not be obtained, but, in fact, there is no simple, not letter words, You can try it, in OnCreate, you can't get a long-width value, always 0.
Reason
This is why, in fact, familiar with the view drawing process of friends should be seen at a glance, in OnCreate, our controls are not actually painted well, in other words, the OnCreate method is finished, we define the control will be measured (measure), So we get the height or width of the control in the OnCreate method through View.getheight () is definitely 0.
Solve
NO1:
[Java]View Plaincopyprint?
- 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 simple, we measure it ourselves.
No2:
[Java]View Plaincopyprint?
- 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;
- }
- });
This method, we need to register a Viewtreeobserver listener callback, this listener callback, is dedicated to listen to the drawing, since it is the monitoring of the drawing, then we can naturally obtain the measured value, at the same time, we listen to each monitor before the remove, avoid repeated monitoring.
No3:
[Java]View Plaincopyprint?
- 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 he is the global layout change listener, so it is most recommended to use.
OK, now it seems that the simple question is not so simple.
Above.
How to get to the height of the Android control