原文:http://www.cnblogs.com/zhwl/p/3333585.html
ScrollView与ListView冲突,有时候会导致无法滑动,或者是只显示一行数据,代码如下:
/** * 解决ScrollView嵌套ListView时,会无法正确的计算ListView的大小 * * @param listView */ public void setListViewHeightBasedOnChildren(ListView listView) { // 获取ListView对应的Adapter OrderListAdapter listAdapter = (OrderListAdapter) listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目 View listItem = listAdapter.getView(i, null, listView); // 计算子项View 的宽高 listItem.measure(0, 0); // 统计所有子项的总高度 totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); // listView.getDividerHeight()获取子项间分隔符占用的高度 // params.height最后得到整个ListView完整显示需要的高度 listView.setLayoutParams(params); }
注意:
1.OrderAdapter为你ListView对应的adapter。
2.要注意的是在setAdapter之后调用此方法。
ListView lv = (ListView) getActivity().findViewById(R.id.lv_order); orderListAdapter = new OrderListAdapter(getContext()); lv.setAdapter(orderListAdapter); setListViewHeightBasedOnChildren(lv);
3.有数据的话,在设置数据后调用此方法。
commonProblemAdapter.setData(lists); setListViewHeightBasedOnChildren(lv);
完善工具类(两个ListView之间冲突,设置此方法都能解決):
/** * Created by xiaoMan on 2017/1/20. * Email:1635401972@qq.com * Details:解决ScrollView嵌套ListView时,会无法正确的计算ListView的大小 */ public class ListViewHeighUtils { /** * 解决ScrollView嵌套ListView时,会无法正确的计算ListView的大小 * * @param listView */ public static void setDynamicHeight(ListView listView) { ListAdapter mListAdapter = listView.getAdapter(); if (mListAdapter == null) { // when adapter is null return; } int height = 0; int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED); for (int i = 0; i < mListAdapter.getCount(); i++) { View listItem = mListAdapter.getView(i, null, listView); listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED); height += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = height + (listView.getDividerHeight() * (mListAdapter.getCount() - 1)); listView.setLayoutParams(params); listView.requestLayout(); } }
好了,没了 ==