code
/** * 设置ListView的高度 */ public static void setListViewHeightBasedOnChildren(ListView lv) { ListAdapter listAdapter = lv.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, lv); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = lv.getLayoutParams(); params.height = totalHeight + (lv.getDividerHeight() * (listAdapter.getCount() - 1)); lv.setLayoutParams(params); }
ListView使用的时候一定要嵌套在 LinearLayout 中,因为其他的Layout(如RelativeLayout)没有重写onMeasure(),所以会在onMeasure()时抛出异常,导致重设高度失效。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.jay.myappstudy.SvLvActivity"> <ScrollView android:id="@+id/sv1" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/lv1" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> </ScrollView> </LinearLayout>
page code
mlv1 = findViewById(R.id.lv1); ListViewAdapter adapter = new ListViewAdapter(this, mlv1,R.layout.fruit_item, data2); mlv1.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { } }); mlv1.setAdapter(adapter); Utility.setListViewHeightBasedOnChildren(mlv1);