Butter Knife
Butter Knife,专门为Android View设计的绑定注解,专业解决各种findViewById
。
简介
对一个成员变量使用@BindView
注解,并传入一个View ID, ButterKnife 就能够帮你找到对应的View,并自动的进行转换(将View转换为特定的子类):
class ExampleActivity extends Activity {
@BindView(R.id.title)
TextView title;
@BindView(R.id.subtitle)
TextView subtitle;
@BindView(R.id.footer)
TextView footer; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.bind(this);
// TODO Use fields...
}
}
与缓慢的反射相比,Butter Knife使用再编译时生成的代码来执行View的查找,因此不必担心注解的性能问题。调用bind
来生成这些代码,你可以查看或调试这些代码。
例如上面的例子,生成的代码大致如下所示:
public void bind(ExampleActivity activity) {
activity.subtitle = (android.widget.TextView) activity.findViewById(2130968578);
activity.footer = (android.widget.TextView) activity.findViewById(2130968579);
activity.title = (android.widget.TextView) activity.findViewById(2130968577);
}
资源绑定
绑定资源到类成员上可以使用@BindBool
、@BindColor
、@BindDimen
、@BindDrawable
、@BindInt
、@BindString
。使用时对应的注解需要传入对应的id资源,例如@BindString
你需要传入R.string.id_string
的字符串的资源id。
class ExampleActivity extends Activity {
@BindString(R.string.title)
String title;
@BindDrawable(R.drawable.graphic)
Drawable graphic;
@BindColor(R.color.red)
int red; // int or ColorStateList field
@BindDimen(R.dimen.spacer)
Float spacer; // int (for pixel size) or float (for exact value) field
// ...
}
在非Activity中使用绑定
Butter Knife提供了bind的几个重载,只要传入跟布局,便可以在任何对象中使用注解绑定。
例如在Fragment中:
public class FancyFragment extends Fragment {
@BindView(R.id.button1)
Button button1;
@BindView(R.id.button2)
Button button2; @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fancy_fragment, container, false);
ButterKnife.bind(this, view);
// TODO Use fields...
return view;
}
}
还有一种比较常见的场景,就是在ListView的Adapter中,我们常常会使用ViewHolder:
public class MyAdapter extends BaseAdapter {
@Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view != null) {
holder = (ViewHolder) view.getTag();
} else {
view = inflater.inflate(R.layout.whatever, parent, false);
holder = new ViewHolder(view);
view.setTag(holder);
} holder.name.setText("John Doe");
// etc... return view;
} static class ViewHolder {
@BindView(R.id.title)
TextView name;
@BindView(R.id.job_title)
TextView jobTitle; public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
ButterKnife.bind
的调用可以被放在任何你想调用findViewById
的地方。
提供的其他绑定API:
使用Activity作为跟布局在任意对象中进行绑定。如果你使用了类似MVC的编程模式,你可以对controller使用它的Activity用
ButterKnife.bind(this, activity)
进行绑定。使用
ButterKnife.bind(this)
绑定一个布局的子布局。如果你在布局中使用了<merge>
标签并且在自定义的控件构造时inflate这个布局,你可以在inflate之后立即调用它。或者,你可以在onFinishInflate()
回调中使用它。
View 列表
你可以一次性将多个views绑定到一个List
或数组中:
@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
List<EditText> nameViews;
apply
函数,该函数一次性在列表中的所有View上执行一个动作:
ButterKnife.apply(nameViews, DISABLE);
ButterKnife.apply(nameViews, ENABLED, false);
Action
和Setter
接口能够让你指定一些简单的动作:
static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {
@Override
public void apply(View view, int index) {
view.setEnabled(false);
}
};
static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() {
@Override
public void set(View view, Boolean value, int index) {
view.setEnabled(value);
}
};
Android中的Property
属性也可以使用apply
方法进行设置:
ButterKnife.apply(nameViews, View.ALPHA, 0.0f);
监听器绑定
使用本框架,监听器能够自动的绑定到特定的执行方法上:
@OnClick(R.id.submit)
public void submit(View view) {
// TODO submit data to server...
}
而监听器方法的参数都时可选的:
@OnClick(R.id.submit)
public void submit() {
// TODO submit data to server...
}
指定一个特定的类型,Butter Knife也能识别:
@OnClick(R.id.submit)
public void sayHi(Button button) {
button.setText("Hello!");
}
可以指定多个View ID到一个方法上,这样,这个方法就成为了这些View的共同事件处理。
@OnClick({ R.id.door1, R.id.door2, R.id.door3 })
public void pickDoor(DoorView door) {
if (door.hasPrizeBehind()) {
Toast.makeText(this, "You win!", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Try again", LENGTH_SHORT).show();
}
}
自定义View时,绑定事件监听不需要指定ID
public class FancyButton extends Button {
@OnClick
public void onClick() {
// TODO do something!
}
}
重置绑定:
Fragment的生命周期与Activity不同。在Fragment中,如果你在onCreateView
中使用绑定,那么你需要在onDestroyView
中设置所有view为null
。为此,ButterKnife返回一个Unbinder
实例以便于你进行这项处理。在合适的生命周期回调中调用unbind
函数就可完成重置。
public class FancyFragment extends Fragment {
@BindView(R.id.button1)
Button button1;
@BindView(R.id.button2)
Button button2;
private Unbinder unbinder; @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fancy_fragment, container, false);
unbinder = ButterKnife.bind(this, view);
// TODO Use fields...
return view;
} @Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
}
可选绑定:
在默认情况下, @bind
和监听器的绑定都是必须的,如果目标view没有找到的话,Butter Knife将会抛出个异常。
如果你并不想使用这样的默认行为而是想创建一个可选的绑定,那么你只需要在变量上使用@Nullable
注解或在函数上使用@Option
注解。
注意:任何名为@Nullable
的注解都可以使用在变量上。但还时强烈建议使用Android注解库中的@Nullable
。
@Nullable
@BindView(R.id.might_not_be_there)
TextView mightNotBeThere; @Optional
@OnClick(R.id.maybe_missing)
void onMaybeMissingClicked() {
// TODO ...
}
对于包含多个方法的监听
当一个监听器包含多个回调函数时,使用函数的注解能够对其中任何一个函数进行绑定。每一个注解都会绑定到一个默认的回调。你也可以使用callback
参数来指定一个其他函数作为回调。
@OnItemSelected(R.id.list_view)
void onItemSelected(int position) {
// TODO ...
} @OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED)
void onNothingSelected() {
// TODO ...
}
Butter Knife提供了一个findViewById
的简化代码:findById
,用这个方法可以在View
、Activity
和Dialog
中找到想要View,而且,该方法使用的泛型来对返回值进行转换,也就是说,你可以省去findViewById
前面的强制转换了。
View view = LayoutInflater.from(context).inflate(R.layout.thing, null);
TextView firstName = ButterKnife.findById(view, R.id.first_name);
TextView lastName = ButterKnife.findById(view, R.id.last_name);
ImageView photo = ButterKnife.findById(view, R.id.photo);
Butter Knife的更多相关文章
- Android:Butter Knife 8.0.1配置
github地址:https://github.com/GarsonZhang/butterknife Butter Knife Field and method binding for Androi ...
- [轉]Android Libraries 介紹 - Butter knife
原文地址 Butter Knife 簡介 Butter Knife - Field and method binding for Android views.助你簡化程式碼,方便閱讀. 使用方法 開發 ...
- android注解[Jake Wharton Butter Knife]
Introduction Annotate fields with @InjectView and a view ID for Butter Knife to find and automatical ...
- Butter Knife使用详解
Butter Knife Github地址: https://github.com/JakeWharton/butterknife 官方说明给出的解释是 Bind Android views and ...
- Butter Knife 使用方法
获取控件 @InjectView(R.id.image_show_password)ImageView image_show_password; 控件事件 @OnClick(R.id.btn_subm ...
- Android RoboGuice开源框架、Butter Knife开源框架浅析
Google Guice on Android(RoboGuice) 今天介绍一下Google的这个开源框架RoboGuice, 它的作用跟之前讲过的Dagger框架差点儿是一样的,仅仅是Dagger ...
- android Butter Knife 使用详解
Butter Knife github连接:https://github.com/JakeWharton/butterknife 本文使用的butterknife版本7.0.1 butterknife ...
- Butter Knife 黄油刀
简介 Github:https://github.com/JakeWharton/butterknife 文档 特点: 采用注解的方式实现强大的View绑定和Click事件处理功能,简化代码,提升开 ...
- Butter Knife:一个安卓视图注入框架
Butter Knife:一个安卓视图注入框架 2014年5月8日 星期四 14:52 官网: http://jakewharton.github.io/butterknife/ GitHub地址: ...
- Android Studio & Butter Knife —— 快速开发
Butter Knife是一个Android的注解框架,可以帮助用户快速完成视图.资源与对象的绑定,完成事件的监听.(也就是少写findViewById()) 具体的介绍可以参考官方主页: http: ...
随机推荐
- Storm VS Flink ——性能对比
1.背景 Apache Flink 和 Apache Storm 是当前业界广泛使用的两个分布式实时计算框架.其中 Apache Storm(以下简称"Storm")在美团点评实时 ...
- 为什么说 Java 程序员必须掌握 Spring Boot ?(转)
Spring Boot 2.0 的推出又激起了一阵学习 Spring Boot 热,那么, Spring Boot 诞生的背景是什么?Spring 企业又是基于什么样的考虑创建 Spring Boot ...
- windows 服务 安装、卸载
1.新建项目 选中windows服务 2.添加安装程序 3.修改安装代码 ServiceProcessInstaller processInstall; ServiceInstaller servic ...
- 上传文件的C#代码
1 <%@ WebHandler Language="C#" Class="UpLoadFile" %> 2 3 using System; 4 u ...
- Alodi:为了保密我开发了一个系统
每天都在愉快的造轮子,这次可以一键创建测试环境 咖啡君维护了几十个不同类型项目,其中有相当一部分项目是对保密性有很高要求的,也就是说下个版本要上线的内容是不能提前泄露的,就像苹果新产品的介绍网站决不允 ...
- postman--请求以及变量设置的实例练习
我们可以在2个地方添加需要执行的js脚本,一个是Pre-request Script,还有一个tests,我们先看请求之前的 1 在请求被发送到服务器之前:就是在“Pre-request Script ...
- Linux 笔记 - 几个常用且重要的命令
博客地址:http://www.moonxy.com Linux 系统中提供了大量的命令,从文件目录管理,用户管理,到系统监控等等,功能非常丰富,但有几个是常用且重要的命令. 1. 命令 grep 作 ...
- centos下nc的安装和使用
安装:yum install nc.x86_64 发送文件: nc -l port < somefile.xxx 接收文件: nc -n x.x.x.x port > somefile.x ...
- java架构之路-(spring源码篇)由浅入深-spring实战详细使用
今天我更新了一篇jvm垃圾回收的算法和垃圾回收器的内部逻辑,但是看的人不多啊......貌似大家还是比较喜欢看源码吧,毕竟实战要比理论用的多. 这篇文章不会详细的深入底层源码,只是基于注解和配置来说说 ...
- 记录工作中groovy动态生成Flink任务
工作中的痛点:有一个计算的任务,需要配置成前端配置好一些简单的信息,例如名字,计算间隔,计算规则(这个是需要提前写好,开放给用户选择的),然后通过提交到我们的计算引擎中心生成对应的任务jar包提交到服 ...