ScrollView嵌套listView/gridView的坑

作者: 汉之风云 | 来源:发表于2016-03-11 00:15 被阅读790次

问题: 为什么scrollView中的listView/gridView只显示一行?

原因:由于listView/gridView在scrollView中无法正确计算它的大小, 故只显示一行.

最佳解决方案:

重写ListView, 覆盖onMeasure()方法:设置让listView能有多高就多高.

public class WrapListView extends ListView{


    public WrapListView(Context context) {
        super(context);
    }

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

    public WrapListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


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

gridView与listView相同:

public class WrapGridView extends GridView{


    public WrapGridView(Context context) {
        super(context);
    }

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

    public WrapGridView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


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

不重写ListView的方案

private void setListViewHeight(ListView listView) {

    ListAdapter listAdapter = listView.getAdapter();

    if (listAdapter == null) {    
            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标签替换即可

希望对大家的学习有所帮助~~~

相关文章

网友评论

  • bacy_love:第二种方法没卡死吗?
    view创建两次。。。
    bacy_love:看for循环里面getview,每次都new了一个view
    bacy_love:@bacy_love 看for循环里面getview,每次都new了一个view
    汉之风云:@bacy_love 没有啊, 只是动态设置listView的高度
  • yzytmac:长期关注哟大神,这个问题我们老师也讲过,但没讲第二种方法,谢谢咯,多发点干活哈!
    汉之风云:@雨小七 谢谢支持~加油

本文标题:ScrollView嵌套listView/gridView的坑

本文链接:https://www.haomeiwen.com/subject/ftwtlttx.html