Dynamically sets the height of the GridView, fixed column, and sets the height according to the item number in the GridView:
Call the following methods:
[Java]View Plaincopy
- Public static void Setlistviewheightbasedonchildren (GridView listView) {
- //Get the adapter of the ListView
- ListAdapter listadapter = Listview.getadapter ();
- if (listadapter = = null) {
- return;
- }
- //Fixed column width, how many columns
- int col = 4; Listview.getnumcolumns ();
- int totalheight = 0;
- //I add 4 each time, equivalent to Listadapter.getcount () is less than or equal to 4 o'clock cycles once, the height of the item is calculated once ,
- //Listadapter.getcount () less than or equal to 8 o'clock calculates two times the height addition
- For (int i = 0; i < listadapter.getcount (); i + = col) {
- //Get every item in a ListView
- View ListItem = Listadapter.getview (i, null, ListView);
- Listitem.measure (0, 0);
- //Get the item's height and
- Totalheight + = Listitem.getmeasuredheight ();
- }
- //Get the layout parameters of the ListView
- Viewgroup.layoutparams params = Listview.getlayoutparams ();
- //Set height
- Params.height = Totalheight;
- //Set margin
- ((marginlayoutparams) params). SetMargins (Ten, ten, 10);
- //Set parameters
- Listview.setlayoutparams (params);
- }
After calling this method, you need to invoke the Notifydatasetchanged () method to implement the interface refresh
Android dynamically sets the GridView height, fixed column, for highly adaptive