If the root view of this item must be LinearLayout
PackageCom.bxg.news.view;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.ListAdapter;ImportAndroid.widget.ListView; Public class Utility { Public Static void Setlistviewheightbasedonchildren(ListView ListView, View v) {//Get ListView corresponding AdapterListAdapter listadapter = Listview.getadapter ();if(ListAdapter = =NULL) {//Pre-condition return; }intTotalheight =0; for(inti =0, Len = Listadapter.getcount (); i < Len; i++) {//Listadapter.getcount () returns the number of data itemsView ListItem = Listadapter.getview (i,NULL, ListView); Listitem.measure (0,0);//Calculate the width height of the child viewTotalheight + = Listitem.getmeasuredheight ();//Statistics total height of all children}if(V! =NULL) {totalheight + = V.getheight (); } viewgroup.layoutparams params = Listview.getlayoutparams (); Params.height = Totalheight + (listview.getdividerheight () * (Listadapter.getcount ()-1)) +Ten;//Listview.getdividerheight () Gets the height of the delimiter between children //Params.height finally get the entire ListView full display required heightListview.setlayoutparams (params); }}
It is important to note that:
If TextView is a multi-line time. Need to override Onmeasure method for TextView
protected void onmeasure(intWidthmeasurespec,intHEIGHTMEASURESPEC) {Super. Onmeasure (Widthmeasurespec, Heightmeasurespec); Layout layout = GetLayout ();if(Layout! =NULL) {intHeight = (int) Floatmath.ceil (Getmaxlineheight ( This. GetText (). toString ()) + getcompoundpaddingtop () + Getcompoundpaddingbottom ();intwidth = Getmeasuredwidth (); Setmeasureddimension (width, height); } }Private float Getmaxlineheight(String str) {floatHeight =0.0FfloatScreenw = (Activity) context). Getwindowmanager (). Getdefaultdisplay (). GetWidth ();floatPaddingleft = ((relativelayout) This. GetParent ()). Getpaddingleft ();floatPaddingreft = ((relativelayout) This. GetParent ()). Getpaddingright ();//Here specific This.getpaint () to pay attention to use, to see where your textview, this is to take the TextView parent control of padding, in order to more accurately calculate the line break intLine = (int) Math.ceil ( This. Getpaint (). Measuretext (str)/(screenw-paddingleft-paddingreft)); Height = ( This. Getpaint (). Getfontmetrics (). Descent- This. Getpaint (). Getfontmetrics (). Ascent) * Line;returnHeight }
To determine each item height of a ListView