##***Scrollview和ExpandableListView嵌套显示不全***

- 当我们将ExpandableListView嵌套在Scrollview之中时,我们必须要确保我们的不居中ExpandableListView在最后

- 在OnCreate()方法中要用到的代码

mListView = (ExpandableListView) findViewById(R.id.activity_expandable_list_view);
        MyExpandableListAdapter adapter = new MyExpandableListAdapter(this,
                mGroups);
        mListView.setAdapter(adapter);
        mListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
 
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                setListViewHeight(parent, groupPosition);
                return false;
            }
        });

- 还必须用到的方法如下:

其中,group为一级条目当前的位置,如果不是在onGroupClick()方法中调用,则不用传group参数,也不做if判断。

/**设置listview的高度,解决嵌套在ScrollView中显示不全的问题*/

private void setListViewHeight(ExpandableListView listView, int group){
        //得到相应ListView的适配器
        ExpandableListAdapter listAdapter = listView.getExpandableListAdapter();
        //总高度
        int totalHeight = 0;
        //期望的宽度
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.EXACTLY);
        for (int i = 0; i < listAdapter.getGroupCount(); i++) {
            //得到一级条目
            View groupItem = listAdapter.getGroupView(i, false, null, listView);
            //groupItem根据给的参数测量一下尺寸,方法调用完后groupItem大小就确定了
            groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            //累加一级条目高度
            totalHeight += groupItem.getHeight();
            //    除了group条目外都展开了  或者  group那一条目没有展开
            if (((listView.isGroupExpanded(group))&&(i!=group)) ||((!listView.isGroupExpanded(group))&&(i == group)) ) {
                for (int j = 0; j < listAdapter.getChildrenCount(i); j++) {
                    //得到二级条目
                    View listItem = listAdapter.getChildView(i, j, false, null, listView);
                    //listItem根据给的参数测量一下尺寸,方法调用完后listItem大小就确定了
                    listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                    //累加二级条目高度
                    totalHeight += listItem.getHeight();
                }
            }
        }
        //获得listView的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        //listView的高度 = 一级条目和二级条目总和 + 分割线高度总和
        int height = totalHeight + (listView.getDividerHeight()*(listAdapter.getGroupCount() - 1));
        //如果高度小于10,则设置为200,没有太大关系
        if(height < 10){
            height = 200;
        }
        //把高度赋值给布局参数
        params.height = height;
        //把布局参数回传给listView
        listView.setLayoutParams(params);
        //listView按照参数从新布局
        listView.requestLayout();
    }

04-14 03:02