Java Annotation简化findViewById

直接贴代码

/**
 * @author huangbo 
 */
public class ViewFindUtil {
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ViewId {
        int value();
    }

    /**
     *
     * @param object the object whose field should be modified
     * @param root
     */
    public static void findViews(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;

        public ViewHolder(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");

猜你喜欢

转载自blog.csdn.net/huagbo/article/details/74202539