ScrollView中嵌套ListView我測試時,若是高度顯示用布局調整android:layout_height=""不管用了,那么這里提供給大家提供兩種方法:
方法一:通過在Activity中計算ListView的item高度,并重新布局
int totalHeight = 0;for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回數據項的數目 View listItem = listAdapter.getView(i, null, listView); // 計算子項View 的寬高 listItem.measure(0, 0); // 統計所有子項的總高度 totalHeight += listItem.getMeasuredHeight();}ViewGroup.LayoutParams params = listView.getLayoutParams();params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));// listView.getDividerHeight()獲取子項間分隔符占用的高度// params.height最后得到整個ListView完整顯示需要的高度listView.setLayoutParams(params); //內部會自動調用listView.requestLayout();重新布局方法二:自定義ListView,重寫onMeasure()方法
@Override PRotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //首次改變顯示尺寸是在布局中直接設置的,第二次改變尺寸地方是這里,而第三次改變尺寸可在Activity中 int spec = MeasureSpec.makeMeasureSpec(422, MeasureSpec.AT_MOST); setMeasuredDimension(widthMeasureSpec,spec); //或采用下邊這種方式// int spec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);// setMeasuredDimension(widthMeasureSpec,heightMeasureSpec); }其實這種情況不一定會出現的,下邊的滑動問題才是重點哦!
不能滑動問題
需要注意的是:
1.滑動的前提是listView的高度顯示不下所有的數據內容。
2.一次觸摸事件(包括按下、滑動、抬起)只有落到listView的覆蓋范圍,listView才會監聽到。
3.上次的觸摸事件的處理方式(如請求父控件不攔截),不會影響下一次觸摸事件的處理。
三種處理滑動問題的方法:
方法一,設置setOnTouchListener:
listView.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_UP){ listView.requestDisallowInterceptTouchEvent(false); //請求控件不攔截本次觸摸事件 }else{ listView.requestDisallowInterceptTouchEvent(true); } return false; }});方法二,自定義ListView,重寫onInterceptTouchEvent或dispatchTouchEvent方法:
@Override public boolean onInterceptTouchEvent(MotionEvent ev) { int action = ev.getAction(); switch(action) { case MotionEvent.ACTION_DOWN : requestDisallowInterceptTouchEvent(true); break; case MotionEvent.ACTION_UP: requestDisallowInterceptTouchEvent(false); break; } return true; }方法三:
@Overridepublic boolean onInterceptTouchEvent(MotionEvent ev) { requestDisallowInterceptTouchEvent(true); return super.onInterceptTouchEvent(ev); //或采用 return true;}總結:
還是留給優秀的你來完成吧!O(∩_∩)O哈哈~
新聞熱點
疑難解答