• ScrollView嵌套ListView只显示一行解决方案


    在ScrollView里边嵌套了个ListView,后边就发现数据源里好多数据,但ListView只是显示1行。
    各种debug,打log,数据什么的都没问题,上网百度了下,发现原来是ScrollView嵌套ListView的一个Bug。
    在ScrollView中嵌套ListView空间,无法正确的计算ListView的大小,故可以通过代码,根据当前的ListView的列表项计算列表的尺寸。

    实现代码如下: 
    private void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
    // pre-condition
    return;
    }

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

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    }


    在ListView声明之后调用就可以了。

    还有更简单的方法:不需要硬着算,只需要自定义ListView,重写下OnMeasured方法就好了

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





  • 相关阅读:
    UITextField的总结
    【实战】登录界面
    点分治学习
    2020/3/1
    2020/2/29
    2020/2/28
    2020/2/27
    2020/2/27
    最小树形图
    Ch’s gift HDU6162
  • 原文地址:https://www.cnblogs.com/jeffen/p/6612751.html
Copyright © 2020-2023  润新知