Viewtreeobserver helps to get the width of a widget

Source: Internet
Author: User

Sometimes you need to know the width and height of a view component in the oncreate method, and directly call the getwidth (), getheight (), getmeasuredwidth (), getmeasuredheight () gettop (), getleft (), and other methods cannot obtain the actual value, and only 0 is obtained. This is because the view component layout must be completed after the onresume callback. The implementation method is provided below. The ongloballayout callback is automatically called when the view layout is complete:


For example:

// This listener is used to get the final width of the gridview and then calculate the // Number of columns and the width of each column. the width of each column is variable // as the gridview has stretchmode = columnwidth. the column width is used to set the height // of each view so we get nice square thumbnails. mgridview. getviewtreeobserver (). addongloballayoutlistener (// called when the view layout is complete. New viewtreeobserver is called every time the view changes. ongloballayoutlistener () {@ overridepublic void ongloballayout () {If (madapter. getnumcolumns () = 0) {final int numcolumns = (INT) math. floor (mgridview. getwidth ()/(mimagethumbsize + mimagethumbspacing); If (numcolumns> 0) {<span style = "white-space: pre "> </span> final int columnwidth = (mgridview. getwidth ()/numcolumns)-mimagethumbspacing; madapter. setnumcolumns (numcolumns); // you can specify the number of madapter columns. setitemheight (columnwidth); // set height }}}});

After the layout of the gridview is complete, set the number of adapter columns and the height of each item based on the width and height of the girdview.

Viewtreeobserver helps to get the width of a widget

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.