Android註解式綁定控件

一般的綁定

headPicture = (ImageView)findViewById(R.id.UserHeadPicture);


註解式綁定

1)     導butterknife.BindView包:http://jingyan.baidu.com/article/48b37f8d37ca921a64648833.html

2)     編寫處理註解的方法(直接粘貼就可以,沒有什麼特別的地方):

public static void initBindView(Object currentClass){
    Field[] fields = currentClass.getClass().getDeclaredFields();
    if (fields != null && fields.length > 0){
        for (Field field : fields){
            if (field.isAnnotationPresent(BindView.class)){
                BindView bindView = field.getAnnotation(BindView.class);
                int viewId = bindView.value();
                try{
                    field.setAccessible(true);
                    field.set(currentClass, ((Activity)currentClass).findViewById(viewId));
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

3)     調用上面的方法(要在setContentView()方法調用之後)

ButterKnife.bind(this);
initBindView(this);

4)     之後就可以用這種方式來綁定控件了

@BindView(value = R.id.firstname_edit)
private EditText firstName;

@BindView(value = R.id.lastname_edit)
private EditText lastName;

@BindView(value = R.id.id_edit)
private EditText id;

@BindView(value = R.id.save_btn)
private Button save;

@BindView(value = R.id.read_btn)
private Button read;


發佈了136 篇原創文章 · 獲贊 11 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章