1. 程式人生 > >android listview+popuwindow動態顯示遇到的問題

android listview+popuwindow動態顯示遇到的問題

這兩條折騰listview+popuwindow顯示。

首先遇到listview顯示不正常(寬度總是為matchparent)。

為此在這裡寫上適應PopupWindow和ScrollView的方法——重寫listvie的onMeasure方法,如下:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int maxWidth = meathureWidthByChilds() + getPaddingLeft() + getPaddingRight();
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
       MeasureSpec.AT_MOST);
super.onMeasure(MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.EXACTLY), expandSpec);
}


private int meathureWidthByChilds() {
   int maxWidth = 0;
   View view = null;
   for (int i = 0; i < getAdapter().getCount(); i++) {
       view = getAdapter().getView(i, view, this);
       view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
       if (view.getMeasuredWidth() > maxWidth){
           maxWidth = view.getMeasuredWidth();
       }
   }
   return maxWidth;
}

其實就是為listview重新計算合適的寬和高。

另外還遇到了listview在刪除到item為0後,增加item後getCount個getChildCount一直為0的情況。

糾結了很長時間難過。最後發現http://blog.sina.com.cn/s/blog_682dcc0d010180q2.html。

呼叫listview的requestLayout(),這樣做無非就是擬補資料數量不一致導致報錯

這一句解決了我的問題。