1. 程式人生 > >自定義輕量級android控制元件註解工具--金剪刀(自己命名的)(大家都在用)

自定義輕量級android控制元件註解工具--金剪刀(自己命名的)(大家都在用)

/**
	 * 繫結多個成員變數
	 * 
	 * @param activity
	 *            所在物件
	 */
	private static void bindFields(Activity activity) {

		final Class<? extends Context> clazz = activity.getClass();
		Field[] declaredFields = clazz.getDeclaredFields();

		ArrayList<Integer> filedResIdList = new ArrayList<Integer>();
		ArrayList<String> filedNameList = new ArrayList<String>();
		for (int i = 0; i < declaredFields.length; i++) {
			Field field = declaredFields[i];
			ViewCut injectFiled = field.getAnnotation(ViewCut.class);
			if (injectFiled != null) {

				String filedName = field.getName();
				if (!filedNameList.contains(filedName)) {
					filedNameList.add(filedName);
				}
				int[] resIds = injectFiled.value();

				for (int x = 0; x < resIds.length; x++) {
					int k = resIds[x];
					if (!filedResIdList.contains(k)) {
						filedResIdList.add(k);
					}
				}
			}
		}

		int declaredFieldsLength = filedNameList.size();
		int resIdsLength = filedResIdList.size();

		if (declaredFieldsLength > resIdsLength) {
			throw new InjectException(
					new Throwable(
							"DeclaredFileds' counts  cannot be more than inject ResIds'  counts"));
		} else if (declaredFieldsLength < resIdsLength) {
			throw new InjectException(
					new Throwable(
							"Inject ResIds' counts  cannot be more than DeclaredFileds' counts"));
		}

		for (int i = 0; i < declaredFields.length; i++) {
			Field field = declaredFields[i];
			ViewCut injectFiled = field.getAnnotation(ViewCut.class);
			if (injectFiled != null) {

				int resId = filedResIdList.get(i);
				View view = activity.findViewById(resId);
				field.setAccessible(true);
				try {
					field.set(activity, view);
				} catch (Throwable th) {
					throw new InjectException(
							new Throwable(
									"Inject failed ,maybe your context is null or recorrect"));
				}

			}
		}
	}