通过动态设置ListView高度来解决ScollView与ListView互相嵌套的问题

在布局中经常用到ScrollView+listView嵌套布局来实现页面的滚动但是当动态加载数据的时候listview的显示就不正常了,下面我们来解决这个问题。

在设置了listView.setAdapter(adapter);
后调用下面的方法就可以了

import android.view.ViewGroup.LayoutParams;
/** * 动态设置ListView高度 * @param listView */
    private void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        int count = 20;
        if (listView.getCount() < 20) {
            count = listView.getCount();
        }
        for (int i = 0; i < count; i++) {
            View listItem = listAdapter.getView(i, null, listView);
listItem.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

你可能感兴趣的:(android,Android开发)