ScrollView嵌套listview显示一行bug

首先看看修复bug之后的显示对比图,结果一目了然

显示一行之前

修改bug之后

主要就是ScrollView嵌套listview显示计算  直接上代码   一目了然

 1  <com.wechaotou.utils.MyListView
 2                 android:id="@+id/group_list"
 3                 android:layout_width="match_parent"
 4                 android:layout_height="match_parent"
 5                 android:layout_below="@+id/chat_word"
 6                 android:layout_marginTop="10dp"
 7                 android:divider="#00000000"
 8                 android:paddingBottom="5dp">
 9 
10             </com.wechaotou.utils.MyListView>

 

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

/**
 * Created by hanba on 2019/7/24.
 */

public class MyListView extends ListView {
    public MyListView(Context context) {
        super(context);
    }

    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

 

主要代码就是计算每个listview的高度,代码如下

    public void setListViewHeightBasedOnChildren(ListView listView) {

        // 获取ListView对应的Adapter

        ListAdapter adapter = listView.getAdapter();

        if (adapter == null) {

            return;

        }
        int totalHeight = 0;

        for (int i = 0; i < adapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目

            View listItem = adapter.getView(i, null, listView);

            listItem.measure(0, 0); // 计算子项View 的宽高

            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度

        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (adapter.getCount() - 1));

        // listView.getDividerHeight()获取子项间分隔符占用的高度

        // params.height最后得到整个ListView完整显示需要的高度

        listView.setLayoutParams(params);

    }

最后在listview填充数据的adapter之后调用改方法即可解决bug

    setListViewHeightBasedOnChildren(list);

 

posted @ 2019-08-09 13:33  monkey0928  阅读(258)  评论(0编辑  收藏  举报