ScrollView裏嵌套ListView
開發中總是會遇到一些難以理解的需求,而我們卻不得不去實現該功能,這次遇到的就是在ScrollView中嵌套個垂直的ListView,要說有必要這麼做嗎,listview本來不就可以上下拉麼,只能說ScrollView裏不只有ListView還有別的控件。以下對繼承ListView的上拉加載下拉刷新都適用。因此,懂得事件分發機制很重要。
問題
ListView的高度
裏面ListView的高度如何計算,通常只能顯示ListView的其中一行,解決方法如下:自定義ListView重寫onMeasure方法
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int expandSpec =
MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
ListView的滾動
ListView嵌套在ScrollView中不能滾動,我們就得從 Android事件的分發機制 下手了,要知道,子View可調用requestDisallowInterceptTouchEvent方法,來設置disallowIntercept=true,從而可以阻止父ViewGroup的onInterceptTouchEvent攔截操作。具體操作我們可通過個自定義ListView重寫onInterceptTouchEvent方法,添加如下:
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
setParentNoScrollAble(true);//當手指觸到listview的時候,讓父ScrollView交出ontouch權限,也就是讓父scrollview 停住不能滾動
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
setParentNoScrollAble(false);//當手指鬆開時,讓父ScrollView重新拿到onTouch權限
break;
default:
break;
}
return super.onInterceptTouchEvent(ev);
}
private void setParentNoScrollAble(boolean b) {
// TODO Auto-generated method stub
this.getParent().getParent().requestDisallowInterceptTouchEvent(b);
}
這樣就可以實現當手觸摸到該ListView時,讓父容器ScrollView交出權限,當手指鬆開後,外面的ScrollView就重新獲得權限,也就可以滑動外面了。這裏還要注意一點,ListView最好設置個固定高度值,也可以按上面LIstView設置高度的操作。
ListView中CheckBox記住狀態
我們如果把監聽的代碼放到設置checkbox狀態的代碼之後的話,仍然會 出現checkbox狀態丟失的問題。這是爲什麼?viewholder會緩存item,所以如果監聽寫在後面的話,當初始化checkBox屬性時,由於可能改變其狀態,導致調用了onCheckedChange()方法,而這個監聽器是在上一次初始化的時候添加的,那麼position就是上一次的,不是本次的position,從而導致CheckBox中的狀態錯了。
CheckBox監聽的代碼塊:
holder.my_CheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//進行選中狀態的保存
}
});
CheckBox設置狀態:
holder.my_CheckBox.setChecked(obj.isChosen());//obj.isChosen()是獲取選中的狀態
總結:CheckBox設置狀態 必須 寫在CheckBox監聽的代碼塊 後面
參考鏈接
http://blog.csdn.net/hj363049394/article/details/26590079#
http://blog.csdn.net/footballclub/article/details/43123105