2024-08-05升级问题:Android中ScrollView嵌套listview并解决listview显示问题

问题:

当ScrollView嵌套ListView时,ListView的高度设置为wrap_content时出现ListView的高度不能完全展开,而只显示的第一个Item。

解决方法:

按item的个数乘以高度计算出listview的总高度,并在数据变化时直接设置listview高度,保证完全显示。

具体如下:

1、计算高度:

    private int getListViewHeight(ListView listView){
        ListAdapter listAdapter = listView.getAdapter();
        if(listAdapter==null)
            return 0;

        int totalHeight = 0;
        int itemHeight = 0;
        int count = listAdapter.getCount();
        for(int i=0;i<count;i++){
            View itemView = listAdapter.getView(i,null,listView);
            itemView.measure(0,0);
            itemHeight = itemView.getMeasuredHeight();
            totalHeight += itemView.getMeasuredHeight();
        }

        int dividerHeight = listView.getDividerHeight() * (count-1);
        int itemHeight_1 = listView.getResources().getDimensionPixelSize(R.dimen.gnss_item_height);
        int re = itemHeight_1 * (count+6);
        return re;//(totalHeight + dividerHeight);
    }

2、动态设置控件高度:

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = getListViewHeight(listView);
        listView.setLayoutParams(params);

问题解决。

参考链接:

https://blog.51cto.com/u_16175497/9499844

猜你喜欢

转载自blog.csdn.net/sig321/article/details/141228020