前言
ButterKnife想必大家都不陌生,大大簡化了視圖綁定操作,但畢竟是第三方項目,有些公司出於安全考慮可能不太願意用第三方開源庫,難道就不能“偷懶”了嗎?當然不是,讓我們一起來實現一個簡單的視圖綁定器,和ButterKnife一樣的方便。
實現
創建註解接口
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Bind {
int value();
}
創建註解解析類
public class ViewBinder {
public static void bind(Activity activity) {
bind(activity, activity.getWindow().getDecorView());
}
public static void bind(Object target, View source) {
Field[] fields = target.getClass().getDeclaredFields();
if (fields != null && fields.length > 0) {
for (Field field : fields) {
try {
field.setAccessible(true);
if (field.get(target) != null) {
continue;
}
Bind bind = field.getAnnotation(Bind.class);
if (bind != null) {
int viewId = bind.value();
field.set(target, source.findViewById(viewId));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
使用
Activity
public class BindActivity extends Activity {
@Bind(R.id.tv_test)
TextView tvTest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bind);
ViewBinder.bind(this);
tvTest.setText("test");
}
}
Fragment
public class BindFragment extends Fragment {
@Bind(R.id.tv_test)
TextView tvTest;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_bind, container);
ViewBinder.bind(this, view);
return view;
}
}
ViewHolder
class ViewHolder {
@Bind(R.id.tv_test)
TextView tvTest;
public ViewHolder(View view) {
ViewBinder.bind(this, view);
}
}
其他用法就不過多介紹了,大家自己舉一反三。
用法是不是和ButterKnife一樣簡單!
實現原理
原理其實也很簡單,利用了Android的註解(Annotation)功能,如果大家瞭解註解的用法就可以寫出更多的註解框架。
代碼比較簡單,就不上傳源碼了。
作者:ChayWong
鏈接:https://www.jianshu.com/p/3e0b071c1eb7
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。