1. 程式人生 > >重新測量ListView,GridView的高度

重新測量ListView,GridView的高度

public class CalViewGroupUtil {

	/**
	 * 計算ListView寬高
	 * 
	 * @param listView
	 */
	public static void calListViewWidthAndHeigh(ListView listView) {
		// 獲取ListView對應的Adapter
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		View listItem = null;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回資料項的數目
			 listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 計運算元項View 的寬高
			totalHeight += listItem.getMeasuredHeight(); // 統計所有子項的總高度
		}
		
		//totalHeight += 150;
		int cur = 100;
		if(listAdapter.getCount()<10){
			cur = 60;
		}
		totalHeight += (totalHeight/cur)*(listAdapter.getCount());
		
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() *(listAdapter.getCount())); //(listAdapter.getCount() - 1));
		// listView.getDividerHeight()獲取子項間分隔符佔用的高度
		// params.height最後得到整個ListView完整顯示需要的高度
		listView.setLayoutParams(params);
	}

	/**
	 * 計算GridView寬高
	 * @param gridView
	 */
	public static void calGridViewWidthAndHeigh(int numColumns ,GridView gridView) {
		
		// 獲取GridView對應的Adapter
		ListAdapter listAdapter = gridView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回資料項的數目
			View listItem = listAdapter.getView(i, null, gridView);
			listItem.measure(0, 0); // 計運算元項View 的寬高
			
			if ((i+1)%numColumns == 0) {
				totalHeight += listItem.getMeasuredHeight(); // 統計所有子項的總高度
			}
			
			if ((i+1) == len && (i+1)%numColumns != 0) {
				totalHeight += listItem.getMeasuredHeight(); // 統計所有子項的總高度
			}
		}
		
		totalHeight += 40;

		ViewGroup.LayoutParams params = gridView.getLayoutParams();
		params.height = totalHeight;
		// listView.getDividerHeight()獲取子項間分隔符佔用的高度
		// params.height最後得到整個ListView完整顯示需要的高度
		gridView.setLayoutParams(params);
	}

}