ScrollView與ListView(ExpandableListView)的滑動衝突解決方法
阿新 • • 發佈:2018-12-12
在Android開發中,如果外層使用ScrollView巢狀ListView(ExpandableListView),以下統一稱為ListView,會導致ListView的顯示高度變窄,甚至不能實現螢幕外內容的括展,那麼滑動衝突就出現了。
解決思路:
思路一:
- 在XML中將高度固定(如果ListView中的item不夠多,或者要顯示的內容沒有超出螢幕可以使用)
- 在程式碼中將高度固定,如下所示:
-
public void getHeight(int height){ LayoutParams params=listView.getLayoutParams(); params.width=LayoutParams.MATCH_PARENT; params.height=height; }
思路二:
在程式碼中根據二級條目的個數,動態新增二級條目的高度
public void setHeight(){ int height=0; int count=mAdapter.getCount();//如果是ExpandableListView-->count=getGroupCount(); for(int i=0;i<count;i++){ View view=mAdapter.getView(i,null,mListView);//如果是ExpandableListView-->mAdapter.getGroupView(i,null,mExpandableListView); view.measure(0,0); height+=view.getMeasuredHeight;//獲取onMeasure過程中要顯示的子條目的高度,從第i個條目開始增加高度 } LayoutParams params=mListView.getLayoutParams(); params.width=LayoutParams.MATCH_PARENT; params.height=height; mListView.setLayoutParams(params): }
注意:setHeight()方法要放在第一級條目的點選事件中
下面是部分完整的程式碼-->
boolean isExpand =false; final int count=mExpandAdapter.getGroupCount(); int height1=0; int height2=0; for(int i=0;i<count;i++){ final View view=mExpandAdapter.getGroupCount(i,null,mExpandableListView); view.measure(0,0); height2=view.getMeasuredHeight(); height1+=view.getMeasuredHeight(); } LinearLayout.LayoutParams params=mExpandableListView.getLayoutParams(); param.width=LinearLayout.LayoutParams.MATCH_PARENT; params.height=height1; mExpandableListView.setLayoutParams(params); final int finalHeight=height1; final int finalHeight2=height2; mExpandableListView.setOGroupClickListener(new ExpandableListView.OnGroupClickListener(){ @Override public boolean onGroupClick(ExpandableListView parent,View v,int groupPosition,long id){ int childSize=parentList.get(groupPosition).getChildList().size(); if(!isExpand){ LinearLayout.LayoutParams params=mExpandableListView.getLayoutParams(); params.width=LinearLayout.LayoutParams.MATCH_PARENT; params.height=finalHeight+finalHeight*childSize;//*******重點 1 mExpandableListView.setLayoutParams(params); }else{ LinearLayout.LayoutParams params =mExpandableListView.getLayoutParams(); params.width=LinearLayout.LayoutParams.MATCH_PARENT; params.height=finalHeight;//********重點 2 mExpandableListView.setLayoutParams(params); } return false; });
最好是親自敲一下程式碼感受下.