Example:
1. MainActivity code:
Public class MainActivity extends Activity {// you only need to call this static method Utility after setting the ListView Adapter. setListViewHeightBasedOnChildren (listview); // You can correctly display the ListView in the ListItem of its parent ListView. // But note that each Item in the sublistview must be LinearLayout and cannot be other items, because other Layout (such as RelativeLayout) // onMeasure () is not overwritten (), therefore, an exception is thrown during onMeasure. Private ArrayList <String> dataList; private ListView listview; private ImageView img; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); dataList = new ArrayList <String> (); for (int I = 0; I <5; I ++) {String str = "row" + I + "; dataList. add (str);} img = (ImageView) findViewById (R. id. imageView1); listview = (ListView) findViewById (R. id. listView1); listview. setAdapter (new BaseAdapter () {@ Override public View getView (int position, View convertView, ViewGroup parent) {LayoutInflater inflater = getLayoutInflater (); View layout = inflater. inflate (R. layout. item, null); TextView TV = (TextView) layout. findViewById (R. id. TV _item); String str = dataList. get (position); TV. setText (str); return layout ;}@ Override public long getItemId (int position) {return 0 ;}@ Override public Object getItem (int position) {return null ;} @ Override public int getCount () {return dataList. size () ;}}); Utility. setListViewHeightBasedOnChildren (listview );}}
2. Utility code
public class Utility{ public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); }}
This article is from the "no trace in the sky but I fly over" blog. For more information, contact the author!