Scrollview嵌套ExpandableListView 的方法

转至 http://stackoverflow.com/questions/17696039/expandablelistview-inside-a-scrollview

                      最近在学习android APK,试着写了一个demo,里面涉及到Scrollview嵌套ExpandableListView的使用,从网上找了一些方法,最后综合整理的一下。


private void setListViewHeight(ListView listView) {
	    ListAdapter listAdapter = listView.getAdapter();
	    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.requestLayout();
	}
    
    private void setListViewHeight(ExpandableListView listView,int group) {
	    ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter();
	    int totalHeight = 0;
	    int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(),
	    MeasureSpec.EXACTLY);
	    for (int i = 0; i < listAdapter.getGroupCount(); i++) {
	    View groupItem = listAdapter.getGroupView(i, false, null, listView);
	    groupItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
	
	    totalHeight += groupItem.getMeasuredHeight();
	
	    if (((listView.isGroupExpanded(i)) && (i != group))
		    || ((!listView.isGroupExpanded(i)) && (i == group))) {
			    for (int j = 0; j < listAdapter.getChildrenCount(i); j++) {
				    View listItem = listAdapter.getChildView(i, j, false, null,
				    listView);
				    listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
				
				    totalHeight += listItem.getMeasuredHeight();
			
			    }
		    }
	    }
	
	    ViewGroup.LayoutParams params = listView.getLayoutParams();
	    int height = totalHeight + (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
	    if (height < 10)
	    	height = 200;
	    params.height = height;
	    listView.setLayoutParams(params);
	    listView.requestLayout();

    }   

重写两个方法

       mGattServicesList = (ExpandableListView) findViewById(R.id.gatt_services_list);  

       mGattServicesList.setOnGroupExpandListener(new OnGroupExpandListener(){
        	@Override
        	public void onGroupExpand(int groupPosition) {
        		setListViewHeight(mGattServicesList);
        	}        		
        });
        
        mGattServicesList.setOnGroupCollapseListener(new OnGroupCollapseListener(){
			@Override
			public void onGroupCollapse(int groupPosition) {
				// TODO Auto-generated method stub
				setListViewHeight(mGattServicesList);
			}        		
        });
调用时机:

     1.在setAdapter后

     

        mGattServicesList.setAdapter(gattServiceAdapter);
        setListViewHeight(mGattServicesList);

   2.在上面的
       setOnGroupExpandListener和setOnGroupCollapseListener 两个注册事件中


你可能感兴趣的:(Scrollview嵌套ExpandableListView 的方法)