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