Android使用註解避免大量的findViewById()

BindView註解類
@Target(ElementType.FIELD)//表示要註解的是一個字段
@Retention(RetentionPolicy.RUNTIME)

//添加@interface表明這是一個註解,等價於繼承了java.lang.annotation.Annotation這個類
public @interface BindView {
    public int id();//viewid

    public boolean clickable() default false;//是否可點擊,默認爲false
}

使用
public class AnnotationActivity extends Activity implements View.OnClickListener {

    @BindView(id = R.id.text_anno, clickable = true)
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_annotation);

        initView(this, findViewById(android.R.id.content));
    }

    private void initView(Object viewClass, View view) {
        Field[] fields = viewClass.getClass().getDeclaredFields();
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                BindView bindView = field.getAnnotation(BindView.class);
                if (bindView != null) {
                    int id = bindView.id();
                    boolean clickable = bindView.clickable();
                    try {
                        field.setAccessible(true);
                        if (clickable) {
                            view.findViewById(id).setOnClickListener((View.OnClickListener) viewClass);
                        }
                        //viewClass中的field賦值爲view.findViewById(id)
                        field.set(viewClass, view.findViewById(id));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(this, "click!", Toast.LENGTH_SHORT).show();
        textView.setText("click");
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章