First, ListView cannot be used directly, to customize one, and then rewrite the Onmeasure () method:
Copy Code code as follows:
@Override
protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {
int expandspec = Measurespec.makemeasurespec (Integer.max_value >> 2,
Measurespec.at_most);
Super.onmeasure (Widthmeasurespec, Expandspec);
}
Step Two: Write a method to calculate ListView per item:
Copy Code code as follows:
public void Setlistviewheightbasedonchildren (ListView ListView) {
Gets the listview corresponding adapter
ListAdapter listadapter = Listview.getadapter ();
if (ListAdapter = = null) {
Return
}
int totalheight = 0;
for (int i = 0; i < Listadapter.getcount (); i++) {//Listadapter.getcount () returns the number of data items
View ListItem = Listadapter.getview (i, NULL, ListView);
Listitem.measure (0, 0); Calculate the height of a child view
Totalheight + + listitem.getmeasuredheight (); Statistics The total height of all subkeys
}
Viewgroup.layoutparams params = Listview.getlayoutparams ();
Params.height = Totalheight
+ (Listview.getdividerheight () * (Listadapter.getcount ()-1));
Listview.getdividerheight () Gets the height of the delimiter between subkeys
Params.height finally get the entire ListView full display required height
Listview.setlayoutparams (params);
}
Step three: ListView after adding the adapter to set the height:
Copy Code code as follows:
Listview.setadapter (adapter);
New Listviewutil (). Setlistviewheightbasedonchildren (ListView);