ScrollView包含ListView的解决方法

来源:互联网 发布:中信银行网络贷款 编辑:程序博客网 时间:2024/05/29 10:03

第一种方式

动态计算ListView 高度

/** * Scrollview 包含ListView时动态计算Listview的高度 * @param listView */public void setListViewHeightBasedOnChildren(ListView listView) {    // 获取ListView对应的Adapter    ListAdapter listAdapter = 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);}

第二种方式

自定义ListView

public class ListViewForScrollView extends ListView {    public ListViewForScrollView(Context context) {        super(context);    }    public ListViewForScrollView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public ListViewForScrollView(Context context, AttributeSet attrs,                                 int defStyle) {        super(context, attrs, defStyle);    }    @Override    /**     * 重写该方法,达到使ListView适应ScrollView的效果     */    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,                MeasureSpec.AT_MOST);        super.onMeasure(widthMeasureSpec, expandSpec);    }}
原创粉丝点击