Tool class read by Theme

Reading Theme with TypedArray is cumbersome and mechanical. Annotation can be used to get.

  public static void fillObject(Context context, Object object) {
    Class clazz = object.getClass();
    ResIds ids = (ResIds) clazz.getAnnotation(ResIds.class);
    if (ids == null) {
      return;
    }
    Field[] fields = clazz.getFields();
    TypedArray ta =
        context.getTheme().obtainStyledAttributes(ids.ids());
    for (Field field : fields) {
      ResIndex index = field.getAnnotation(ResIndex.class);
      if (index == null) {
        continue;
      }
      field.setAccessible(true);
      try {
        field.setInt(object, ta.getResourceId(index.index(), 0));
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    }
    ta.recycle();
  }

  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.FIELD)
  public @interface ResIndex {
    @StyleableRes
    int index();
  }

  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.TYPE)
  public @interface ResIds {
    @StyleableRes
    int[] ids();
  }

There is a problem: the id in R is not final, you can refer to the processing method of ButterKnife.
Moreover, there is a benefit here, the incoming Object is actually a ViewModel, which can be quickly processed through direct DataBinding.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325837245&siteId=291194637