Android Note: Get the View component width and viewtreeobserver

Source: Internet
Author: User

View Width Height measurement method:

There are three methods of measurement, as follows:

1)(executed directly at OnCreate ())

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 ();  Textview.append (

2)2 and 3 are all after the OnCreate () call callback to get the width of the component

Viewtreeobserver vto = imageview.getviewtreeobserver ();  Vto.addonpredrawlistener (new  Viewtreeobserver.onpredrawlistener () {      public Boolean Onpredraw () {          int height = imageview.getmeasuredheight ();           int width = imageview.getmeasuredwidth ();          Textview.append ("\ n" +height+ "," +width)          ; return true ;      }  

3)

Viewtreeobserver Vto2 = imageview.getviewtreeobserver ();    Vto2.addongloballayoutlistener (new  Ongloballayoutlistener () {      @Override          publicvoid  ongloballayout () {          imageview.getviewtreeobserver (). Removeglobalonlayoutlistener (this);            Textview.append ("\ n" +imageview.getheight () + "," +Imageview.getwidth ())      ;    }

Note: Method One is onmeasure computed one more time than other methods, and the callback function of method Two is called multiple times.

Transfer from http://blog.csdn.net/johnny901114/article/details/7839512

Viewtreeobserver

First, the structure

 Public Final class extends Object    java.lang.Object         android.view.ViewTreeObserver

Ii. Overview

This is an observer (Observer) that registers the listener view tree and is notified when the global event of the view tree is changed. This global event not only includes the entire tree layout, starting with the painting process, changing the touch pattern, and so on. Viewtreeobserver cannot be instantiated by the application because it is provided by the view, referring to Getviewtreeobserver () to see more information.

Iii. Internal class

InterfaceViewtreeobserver.onglobalfocuschangelistener2//The interface class of the callback function to invoke when the focus state in a view tree is changed3 4InterfaceViewtreeobserver.ongloballayoutlistener5//The interface class of the callback function to invoke when the global layout changes in one view tree or the visual state of a view in the View tree changes6 7InterfaceViewtreeobserver.onpredrawlistener8//The interface class of the callback function to invoke when a view tree is about to be drawn9 10InterfaceViewtreeobserver.onscrollchangedlistener11//when some components in a view tree are scrolled, the interface class of the callback function to be called12 13InterfaceViewtreeobserver.ontouchmodechangelistener14//When the touch mode of a view tree changes, the interface class of the callback function to be called

Iv. Public methods

   /**registers a callback function that is called when the focus state in a view tree has changed. 2 * parameter listener the callback function that will be added 3 * Exception illegalstateexception if IsAlive () returns false 4*/5 Public voidAddonglobalfocuschangelistener (Viewtreeobserver.onglobalfocuschangelistener listener)6 7 8/**registers a callback function that is called when the global layout changes in a view tree or when the visual state of a view in the view tree changes. 9 * Parameter listener the callback function that will be added 10 * Exception illegalstateexception if IsAlive () returns FALSE11*/12 Public voidAddongloballayoutlistener (Viewtreeobserver.ongloballayoutlistener listener)13 14 15 16/**registers a callback function that calls this callback function when a view tree is about to be drawn. 17 * Parameter listener the callback function that will be added 18 * Exception illegalstateexception if IsAlive () returns FALSE19*/20 Public voidAddonpredrawlistener (Viewtreeobserver.onpredrawlistener listener)21 22 23/**registers a callback function that calls this callback function when a view is scrolled. 24 * Parameter listener the callback function that will be added 25 * Exception illegalstateexception if IsAlive () returns FALSE26*/27 Public voidAddonscrollchangedlistener (Viewtreeobserver.onscrollchangedlistener listener)28 29 30/**registers a callback function that invokes this callback function when a touch mode change occurs. 31 * Parameter listener the callback function that will be added 32 * Exception illegalstateexception if IsAlive () returns FALSE33*/34 Public voidAddontouchmodechangelistener (Viewtreeobserver.ontouchmodechangelistener listener)35 36 37//notifies the appropriate registration listener when the entire layout has changed. If you force a view layout or a hierarchy of views that are not attached to a window or in the gone state, it can be called manually38 Public Final voiddispatchongloballayout ()39 40/**notifies the appropriate registration listener when a view tree is about to be drawn. If the listener returns True, the drawing will be canceled and re-scheduled. If you force a view layout or a hierarchy of views that are not attached to a window or in a gone state, it can be manually called 41 * The return value currently drawn can be canceled and re-scheduled to return true, otherwise false is returned. the*/43 Public Final BooleanDispatchonpredraw ()44 45/**indicates whether the current Viewtreeobserver is available (alive). When observer is not available, any call to the method (except this method) throws an exception. If an application maintains and viewtreeobserver a long reference, it should always be necessary to detect the return value of the method before calling another method. 46 * Return value but returns true if this object is available, otherwise false*/48 Public BooleanisAlive ()49 50 51/**removes the global layout callback function that was previously registered. 52 * Parameter victim the callback function that will be removed 53 * Exception illegalstateexception if IsAlive () returns false*/55 Public voidRemoveglobalonlayoutlistener (viewtreeobserver.ongloballayoutlistener victim)56 57/**removes the previously registered focus change callback function. 58 * Parameter victim the callback function that will be removed 59 * Exception IllegalStateException if IsAlive () returns false*/61 Public voidRemoveonglobalfocuschangelistener (viewtreeobserver.onglobalfocuschangelistener victim)62 63/**removes pre-drawn callback functions that have been previously registered. 64 * Parameter victim the callback function that will be removed 65 * Exception illegalstateexception if IsAlive () returns false*/67 Public voidRemoveonpredrawlistener (viewtreeobserver.onpredrawlistener victim)68 69/**removes the previously registered scroll change callback function. 70 * Parameter victim the callback function that will be removed 71 * Exception illegalstateexception if IsAlive () returns false*/73 Public voidRemoveonscrollchangedlistener (viewtreeobserver.onscrollchangedlistener victim)74 75/**Remove previously registered touch mode change callback function 76 * parameter victim the callback function that will be removed 77 * Exception illegalstateexception if IsAlive () returns false78*/79 Public voidRemoveontouchmodechangelistener (Viewtreeobserver.ontouchmodechangelistener victim)

Five, code example


1. Creating listeners

Private FinalViewtreeobserver.ongloballayoutlistener Mgloballayoutlistener =NewViewtreeobserver.ongloballayoutlistener () {@Override Public voidongloballayout () {intwidth =-1; intHeight =-1; Try{width=getactivity (). GetWindow (). Getdecorview (). GetWidth (); Height=getactivity (). GetWindow (). Getdecorview (). GetHeight (); } Catch(Exception e) {//called too early. So, just skip.      }            if(Width! =-1 && mgloballayoutwidth! = width) {//updating the UI only makes sense if the dimension really has a value, which is already determinedMgloballayoutwidth =width;      UpdateUI (); } Else if(Height! =-1 && mgloballayoutheight! =height) {Mgloballayoutheight=height; UpdateUI (); } } };

2, generally register the listener in OnCreate or Oncreateview

Mviewtreeobserver = getactivity (). GetWindow (). Getdecorview (). Getviewtreeobserver ();        Mviewtreeobserver.addongloballayoutlistener (Mgloballayoutlistener);

Transferred from Http://www.tuicool.com/articles/fi6BJ3N and http://www.cnblogs.com/xingfuzzhd/archive/2013/06/25/3154674.html

Android Note: Get the View component width and viewtreeobserver

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.