android根据ListView内部Item最大长度来设置ListView的宽度

	/**
	 * 循环找到ListView最大宽度
	 */
	private int getMaxWidth(ListView listView) {
		int maxWidth = 550;
		
		if (listView.getAdapter() == null) {
			return maxWidth;
		}
		
		int count = listView.getAdapter().getCount();
		
		View view = null;
		for (int i = 0; i < count; i++) {
			
			view = listView.getAdapter().getView(i, null, listView);
			view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
					MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
			if (view.getMeasuredWidth() > maxWidth) {
				maxWidth = view.getMeasuredWidth();
			}
		}
		
		if (getActivity().getResources().getDisplayMetrics().widthPixels < maxWidth) {
			return getActivity().getResources().getDisplayMetrics().widthPixels - 50;
		}
		
		return maxWidth;
	}


首先是找到ListAdapter,通过其循环找到最大长度,最后判断最大长度是否超过屏幕长度。

你可能感兴趣的:(Android)