Android dynamically sets the GridView height, fixed column, for highly adaptive

Source: Internet
Author: User

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
  1. Public static void Setlistviewheightbasedonchildren (GridView listView) {
  2. //Get the adapter of the ListView
  3. ListAdapter listadapter = Listview.getadapter ();
  4. if (listadapter = = null) {
  5. return;
  6. }
  7. //Fixed column width, how many columns
  8. int col = 4;   Listview.getnumcolumns ();
  9. int totalheight = 0;
  10. //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 ,
  11. //Listadapter.getcount () less than or equal to 8 o'clock calculates two times the height addition
  12. For (int i = 0; i < listadapter.getcount (); i + = col) {
  13. //Get every item in a ListView
  14. View ListItem = Listadapter.getview (i, null, ListView);
  15. Listitem.measure (0, 0);
  16. //Get the item's height and
  17. Totalheight + = Listitem.getmeasuredheight ();
  18. }
  19. //Get the layout parameters of the ListView
  20. Viewgroup.layoutparams params = Listview.getlayoutparams ();
  21. //Set height
  22. Params.height = Totalheight;
  23. //Set margin
  24. ((marginlayoutparams) params). SetMargins (Ten, ten, 10);
  25. //Set parameters
  26. Listview.setlayoutparams (params);
  27. }

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

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.