利用反射简单实现类似Butterknife

lib-refrection

/**
 * @author : zyl
 * @desc :
 */
public class Binding {

    public static void bind(Activity activity) {
        for (Field field : activity.getClass().getDeclaredFields()) {
            BindView bindView = field.getAnnotation(BindView.class);
            if (bindView != null) {
                try {
                    //类中的成员变量为private,故必须进行此操作
                    field.setAccessible(true);
                    field.set(activity, activity.findViewById(bindView.value()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • 注解
/**
 * @author : zyl
 * @desc :
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface BindView {
    int value();
}

使用方式

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.textView) TextView textView;
    @BindView(R.id.imageView)
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Binding.bind(this);

        textView.setText("Apt");
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                a();
                imageView.setVisibility(View.GONE);
                Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                startActivity(intent);
            }
        });
    }

总结

  • 反射会影响性能(比如一个注解20ms,如果activity里面有100个这样的注解,就会影响到程序。)

你可能感兴趣的:(android,java)