Butter Knife 黄油刀
简介
- 采用注解的方式实现强大的View绑定和Click事件处理功能,简化代码,提升开发效率
- 方便的处理Adapter里的ViewHolder绑定问题
- 是一种依赖注入框架,运行时不会影响APP效率(原理和dagger一样,是在编译期生成代码,与反射没有半毛钱关系)
- 使用配置方便 ,代码清晰,可读性强
- Eliminate消除 findViewById calls by using @BindView on fields.
- Group multiple views组合多个视图 in a list or array. Operate on all of them at once with actions, setters, or properties.
- Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick and others.
- Eliminate resource lookups by using resource annotations on fields.
【如何将注解和字段放在一行】


Gradle配置
//旧版本需在gradle进行好几项配置,新版本只需添加以下两行依赖即可。新版本和旧版本API不一致,建议赶快升级!
compile 'com.jakewharton:butterknife:8.8.1'//2017-9-21最新版本
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'//编译器
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'//每个Android项目默认都会带的
//PS:在新版本中千万不要加这些,日了狗了,加上去之后反而不会生成需要的文件,进而导致完全不能使用ButterKnife。
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'//这个是需要我们手动添加的,apt是用于自动生成代码来进行依赖注入的
}
- 编译时使用该工具,最终打包时不会将该插件打入到apk中。
- 能够根据设置的源路径,在编译时期生成相应代码。
2、在module的build.gradle中添加:
apply plugin: 'com.android.application'//每个Android项目默认都会带的。在build.gradle的第一行
//PS:在新版本中千万不要加这些,日了狗了,加上去之后反而不会生成需要的文件,进而导致完全不能使用ButterKnife。
apply plugin: 'com.neenbedankt.android-apt'//apt支持
compile 'com.jakewharton:butterknife:8.8.1'//2017-9-21最新版本
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'//为编译时期生成代码等相关的类库
Butter Knife中定义的注解



//Bind a field to the view for the specified ID. The view will automatically be cast to the field type.
@Retention(CLASS)
@Target(FIELD)
public @interface BindView {
/** View ID to which the field will be bound. */
@IdRes int value();
}
// Bind a field to the view for the specified ID. The view will automatically be cast to the field type.
@Retention(CLASS) @Target(FIELD)
public @interface BindViews {
/** View IDs to which the field will be bound. */
@IdRes int[] value();
}
@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name }) List<EditText> nameViews;
//Bind a field to the specified string resource ID.
@Retention(CLASS) @Target(FIELD)
public @interface BindString {
/** String resource ID to which the field will be bound. */
@StringRes int value();
}
//Bind a field to a Bitmap from the specified drawable resource ID.
@Retention(CLASS) @Target(FIELD)
public @interface BindBitmap {
/** Drawable resource ID from which the Bitmap will be created. */
@DrawableRes int value();
}
@BindBitmap(R.drawable.logo) Bitmap logo;
//Bind a field to the specified drawable resource ID.
@Retention(CLASS) @Target(FIELD)
public @interface BindDrawable {
/** Drawable resource ID to which the field will be bound. */
@DrawableRes int value();
/** Color attribute resource ID that is used to tint the drawable. */
@AttrRes int tint() default 0;
}
@BindDrawable(R.drawable.placeholder) Drawable placeholder;
@BindDrawable(value = R.drawable.placeholder, tint = R.attr.colorAccent) Drawable tintedPlaceholder;
/**
* Bind a method to an OnClickListener on the view for each ID specified.
* Any number of parameters from OnClickListener#onClick(android.view.View) onClick} may be used on the method.
*/
@Target(METHOD) @Retention(CLASS)
@ListenerClass(
targetType = "android.view.View",
setter = "setOnClickListener",
type = "butterknife.internal.DebouncingOnClickListener",
method = @ListenerMethod(
name = "doClick",
parameters = "android.view.View"
)
)
public @interface OnClick {
/** View IDs to which the method will be bound. */
@IdRes int[] value() default { View.NO_ID };
}
最常使用的注解的示例代码
绑定Activity
public class SimpleActivity extends AppCompatActivity {
@BindView(R.id.text_view) TextView mTextView; //this field should not be declared private or static
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
ButterKnife.bind(this);// ButterKnife.bind(this) should be called after setContentView()
mTextView.setText("View视图的绑定");
}
@OnClick(R.id.button)
void onButtonClick(View view) { //the method should not be declared private or static
//you can write the parameter (View view) as above or just write onButtonClick() leave parameters empty
Toast.makeText(this, "事件绑定", Toast.LENGTH_SHORT).show();
}
}
绑定Fragment
public class SimpleFragment extends Fragment {
@BindView(R.id.text_view) TextView mTextView;
private Unbinder unbinder;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);//标准写法就是这样的
unbinder = ButterKnife.bind(this, view);//绑定Activity为ButterKnife.bind(this);
mTextView.setText("TextView in Fragment are found!");
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
//Fragments have a different view lifecycle than activities.
//When binding a fragment in onCreateView, set the views to null in onDestroyView.
unbinder.unbind();//解除绑定,官方文档只对fragment做了解绑
}
}
绑定Adapter
public class PersonAdapter extends BaseAdapter {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.person_item_layout, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else holder = (ViewHolder) convertView.getTag();
holder.name.setText("包青天");
// etc...
return convertView;
}
static class ViewHolder {
@BindView(R.id.person_name) TextView name;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
绑定资源
@BindView(R.id.app_name) TextView mTextView;//view
@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name }) List<EditText> nameViews;
@BindString(R.string.app_name) String appName;//sting
@BindColor(R.color.red) int textColor;//颜色
@BindBitmap(R.drawable.logo) Bitmap logo;
@BindDrawable(R.drawable.selector_image) Drawable selector;//drawble
@BindDrawable(value = R.drawable.placeholder, tint = R.attr.colorAccent) Drawable tintedPlaceholder;
绑定事件
@OnClick(R.id.submit) void submit(View view) { }
@OnClick(R.id.submit) void sayHi(Button button) { } //定义一个特定类型的View时,它将自动被转换
@OnClick({ R.id.door1, R.id.door2 }) void pickDoor(DoorView door) { } //多个view在一个点击事件中回调
@OnClick(R.id.submit) void submit() { } //参数都是可选的(任何参数都是:如果不需要,可以不写)
@OnItemClick(R.id.my_list_view) void onItemClick(int position) { } //虽然有四个参数, 你可以只写你想要的那个
@OnItemLongClick(R.id.my_list_view) boolean onItmeLongClick(int position) { }//返回true时,整个touch事件结束
//if return false, the onItemClick() will be invoked反射调用 when touch up
public class MyButton extends Button {
@OnClick void onClick() { } //当点击自己时回调
}
@OnTextChanged(value = R.id.mEditText, callback = OnTextChanged.Callback.BEFORE_TEXT_CHANGED)
void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@OnTextChanged(value = R.id.mEditText, callback = OnTextChanged.Callback.TEXT_CHANGED)
void onTextChanged(CharSequence s, int start, int before, int count) { }
@OnTextChanged(value = R.id.mEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
void afterTextChanged(Editable s) { }
官方文档
Introduction
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...
}
}
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);
}
RESOURCE BINDING
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
// ...
}
NON-ACTIVITY BINDING
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;
}
}
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);
}
}
}
- Bind arbitrary objects using an activity as the view root. If you use a pattern like MVC you can bind the controller using its activity with ButterKnife.bind(this, activity).
- Bind a view's children into fields using ButterKnife.bind(this). If you use <merge> tags in a layout and inflate in a custom view constructor you can call this immediately after. Alternatively或者、否则, custom view types (inflated from XML) can use it in the onFinishInflate() callback.
VIEW LISTS
@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name }) List<EditText> nameViews;
ButterKnife.apply(nameViews, DISABLE);
ButterKnife.apply(nameViews, ENABLED, false);
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);
}
};
ButterKnife.apply(nameViews, View.ALPHA, 0.0f);
LISTENER BINDING
@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...
}
@OnClick(R.id.submit)
public void sayHi(Button button) {
button.setText("Hello!");
}
@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();
}
}
public class FancyButton extends Button {
@OnClick
public void onClick() {
// TODO do something!
}
}
BINDING RESET
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();
}
}
OPTIONAL BINDINGS
@Nullable @BindView(R.id.might_not_be_there) TextView mightNotBeThere;
@Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() { }
MULTI-METHOD LISTENERS
@OnItemSelected(R.id.list_view) void onItemSelected(int position) { }
@OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED) void onNothingSelected() { }
BONUS
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:一个安卓视图注入框架
Butter Knife:一个安卓视图注入框架 2014年5月8日 星期四 14:52 官网: http://jakewharton.github.io/butterknife/ GitHub地址: ...
- Android Studio & Butter Knife —— 快速开发
Butter Knife是一个Android的注解框架,可以帮助用户快速完成视图.资源与对象的绑定,完成事件的监听.(也就是少写findViewById()) 具体的介绍可以参考官方主页: http: ...
随机推荐
- Wannafly挑战赛9 D - 造一造
链接:https://www.nowcoder.com/acm/contest/71/D来源:牛客网 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 262144K,其他语言52428 ...
- 百道CTF刷题记录(一)
简介 最近在刷CTF题,主攻Web,兼职Misc Shiyanbar 0x01 简单的登陆题 简单概括: 考点: %00截断正则 CBC字节翻转攻击 难度: 难 WP:https://blog.csd ...
- JFinal框架使用
表单直接提交页面,不用ajax 后台; /** * 修改 */ public void edit() { String id=getPara("id"); String job=g ...
- awk 基本函数用法
gsub函数有点类似于sed查找和替换.它允许替换一个字符串或字符为另一个字符串或字符,并以正则表达式的形式执行.第一个函数作用于记录$0,第二个gsub函数允许指定目标,然而,如果未指定目标,缺省为 ...
- 详细介绍如何在Eclipse中使用SVN
一.在Eclipse中下载安装Subclipse插件 1 打开eclipse,在Help菜单中找到marketPlace,点击进入. 2 在搜索框Find中输入subclipse,点击右边的Go按 ...
- 机器学习之路:python 集成分类器 随机森林分类RandomForestClassifier 梯度提升决策树分类GradientBoostingClassifier 预测泰坦尼克号幸存者
python3 学习使用随机森林分类器 梯度提升决策树分类 的api,并将他们和单一决策树预测结果做出对比 附上我的git,欢迎大家来参考我其他分类器的代码: https://github.com/l ...
- 02-c#基础之01-基础语法(二)
1.变量的存储以及变量的几种类型 变量:用来在计算机当中存储数据. 存储变量的语法: 变量类型 变量名: 变量名=值: int number=100: 2.赋值"=" " ...
- Nodejs线上日志部署
Nodejs 被越来越多的使用到线上系统中,但线上系统没有日志怎么行呢. 一.forever记录日志 我的线上系统使用forever来启动服务,最开始就直接使用了forever来记录 forever ...
- hdu 4277 USACO ORZ DFS
USACO ORZ Time Limit: 5000/1500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total S ...
- C#高级编程9-第5章 泛型
泛型 1.泛型概述 泛型是C#的部分与中间语言IL集成.创建的类或方法指定了类型,在实例化和调用时必须指定类型进行操作. 泛型可以用于类.方法.接口和委托以及结构. 泛型也是结构,同时是运行库CLR定 ...