-
通过代码,根据当前的ListView的列表子项计算列表的高度:
--------------------------------------------------------------
public class MainActivity extends Activity {
private ListView listView;
private String[] adapterData = new String[] { "标题1", "标题2", "标题3"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainActivity);
listView = (ListView) findViewById(R.id.test_listView);
listView.setAdapter(new ArrayAdapter
(this,android.R.layout.simple_list_item_1,adapterData)); fixListViewHeight(listView);
}
public void fixListViewHeight(ListView listView) {
// 如果没有设置数据适配器,则ListView没有子项,返回。
ListAdapter listAdapter = listView.getAdapter();
int totalHeight = 0;
if (listAdapter == null) {
return;
}
for (int index = 0, len = listAdapter.getCount(); i < len; i++) {
View listViewItem = listAdapter.getView(index , null, listView);
// 计算子项View 的宽高
listViewItem.measure(0, 0);
// 计算所有子项的高度和
totalHeight += listViewItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
// listView.getDividerHeight()获取子项间分隔符的高度
// params.height设置ListView完全显示需要的高度
params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}