/**
* @author huangbo
*/publicclassViewFindUtil {@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interfaceViewId {int value();
}
/**
*
* @param object the object whose field should be modified
* @param root
*/publicstaticvoidfindViews(Object object, View root) {
/**
* Returns an array containing {@code Field} objects for all fields declared
* in the class represented by this {@code Class}. If there are no fields or
* if this {@code Class} represents an array class, a primitive type or void
* then an empty array is returned.
*
* @see #getFields()
*/
Field fields[] = object.getClass().getDeclaredFields();
for (Field field : fields) {
/**
* is annotation exist
*/boolean isExist = field.isAnnotationPresent(ViewId.class);
if (!isExist) continue;
ViewId viewId = field.getAnnotation(ViewId.class);
try {
/**
* reset field data
*/
field.setAccessible(true);
field.set(object, root.findViewById(viewId.value()));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
用法
class ViewHolder{
@ViewId(R.id.etNum)/*textView Id*/public TextView textView;
publicViewHolder(View rootView) {
ViewFindUtil.findViews(this,rootView);
}
}
View view=View.inflate(context, R.layout.layout_name,null);
ViewHolder vh= new ViewHolder(view);
vh.textView.setText("success");