Android开发之解决ListView和ScrollView滑动冲突的问题

来源:互联网 发布:光明数据 陈建栋 编辑:程序博客网 时间:2024/06/08 02:06

最近在项目中遇到了如下问题:ScrollView中嵌套2个ListView。当滑动ScrollView的时候,ListView的显示只有1-2个item的问题。上网查过之后,一些解决方案,比如强行设置ListView的高度,还有一些设置ScrollView的监听等方法。不能够解决我的问题。后来还是总结出了两套解决方案。

方案一:自定义ListView,重写onMeasure()方法。

代码如下:

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 defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        heightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }}

在onMeasure方法中,指定ListView的高度。


方案二:创建如下方法并调用。

/**     * 解决ScrollView和ListView滑动冲突的问题,让ListView随着ScrollView一起滑动。     * */    public static void setListViewHeightBasedOnChildren(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, View.MeasureSpec.makeMeasureSpec(0,                    View.MeasureSpec.UNSPECIFIED));            totalHeight += listItem.getMeasuredHeight();        }        ViewGroup.LayoutParams params = listView.getLayoutParams();        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));        listView.setLayoutParams(params);    }


0 0