package com.efounder.chat.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ListView;

/**
 * 宽和高都为wrap_content 的 ListView
 * @author hudq
 *
 */
public class WrapContentListView extends ListView {

	public WrapContentListView(Context context) {
		super(context);
	}
	
	public WrapContentListView(Context context, AttributeSet attrs,
			int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

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


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

	public int measureWidthByChildren() {
		int maxWidth = 0;
		View view = null;
		if (getAdapter() != 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;
	}
}
