Android--------解決ScrollView中嵌套ExpandableListView顯示不全的問題

##***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();
    }ide

相關文章
相關標籤/搜索