1、定义遍历注解类。

public class BindData {
    /**
     * 绑定Activity
     */
    public static void bind(final Activity activity) {
        Class annotationParent = activity.getClass();
        Field[] fields = annotationParent.getDeclaredFields();
        // 找到类里面所有的方法
        if (fields.length > 0) {
            for (Field field : fields) {
                try {
                    field.setAccessible(true);
                    if (field.get(activity) != null) {
                        continue;
                    }
                    ViewData bind = field.getAnnotation(ViewData.class);
                    if (bind != null) {
                        Log.e("wade", field.getType().getName());
                        List<String> data = new ArrayList<>();
                        data.add("12341243");
                        data.add("zhansan");
                        field.set(activity, data);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

2、定义需要注解类的名称

@Retention(RUNTIME)
@Target(FIELD)
public @interface ViewData {
}

3、在主activity中绑定遍历的类,初始化data数据。

class MainActivity : AppCompatActivity() {
    @ViewData
    var data: List<String>? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        BindData.bind(this)
        Log.i(javaClass.name, data.toString())
    }

}

 

相关文章:

  • 2022-12-23
  • 2021-08-05
  • 2021-10-25
  • 2021-10-13
  • 2021-08-15
  • 2021-12-05
猜你喜欢
  • 2021-08-15
  • 2022-12-23
  • 2021-06-14
  • 2021-04-25
  • 2022-02-21
  • 2022-12-23
  • 2021-04-14
相关资源
相似解决方案