范例:

1.MainActivity代码:

public class MainActivity extends Activity{                 //   只要在设置ListView的Adapter后调用此静态方法Utility.setListViewHeightBasedOnChildren(listview);//    即可让ListView正确的显示在其父ListView的ListItem中。//    但是要注意的是,子ListView的每个Item必须是LinearLayout,不能是其他的,因为其他的Layout(如RelativeLayout)//    没有重写onMeasure(),所以会在onMeasure()时抛出异常。                     private ArrayList
dataList; private ListView listview; private ImageView img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dataList = new ArrayList
(); for (int i = 0; i < 5; i++) { String str = "第" + i + "行"; dataList.add(str); } img = (ImageView) findViewById(R.id.p_w_picpathView1); 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代码

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);    }}