自动计算ListView的高度

一般不赞成ScrollView中嵌套ListView,具体可以原因可以自己查下,不在本篇讨论中。我是修改代码的时候发现这个问题,当然不是我写。呵呵,本着我就不信搞不定的决心,网上查询些资料,总有搞定了,网上有好多代码关于计算ListView高度的,像这样的代码一堆一堆的

private void getTotalHeightofListView(ListView listView, Adapter mAdapter) {

    if (mAdapter == null) {
        return;
    }
    int totalHeight = 0;
    for (int i = 0; i < mAdapter.getCount(); i++) {
        View mView = mAdapter.getView(i, null, listView);
        mView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        totalHeight += mView.getMeasuredHeight();
    }
    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (mAdapter.getCount() - 1)
            + Utils.dip2px(getActivity(), 12));
    listView.setLayoutParams(params);
    listView.requestLayout();
}    

但是,只要是item的高度不一样的时候就有问题了 。所以才有了下边的代码,直接重写下ListView的onMeasure方法就搞定。

/**
 * 自动计算listview的高度
 * 
 */
public class AutoCountListView extends ListView{

 public AutoCountListView(Context context){
      super(context);
 }

 public AutoCountListView(Context context, AttributeSet attrs){
      super(context, attrs);
 }

 public AutoCountListView(Context context, AttributeSet attrs, int defStyle){
      super(context, attrs, defStyle);
 }

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
      // TODO Auto-generated method stub
      int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
        MeasureSpec.AT_MOST);
      super.onMeasure(widthMeasureSpec, expandSpec);
 }
}

顺便普及下 makeMeasureSpec(int size, int mode) 的几种 mode

makeMeasureSpec(int size, int mode)
Creates a measure specification based on the supplied size and mode.

AT_MOST    Measure specification mode: The child can be as large as it wants up to the specified size.

EXACTLY    Measure specification mode: The parent has determined an exact size for the child.

UNSPECIFIED    Measure specification mode: The parent has not imposed any constraint on the child.
梦想还是要有的,万一实现了呢?