Introduction
Annotate fields with @BindView and a view ID for Butter Knife to find and automatically cast the corresponding view in your layout. 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...
}
}
Instead of slow reflection, code is generated to perform the view look-ups. Calling bind delegates to this generated code that you can see and debug. The generated code for the above example is roughly equivalent to the following: 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
Bind pre-defined resources with @BindBool, @BindColor, @BindDimen, @BindDrawable, @BindInt, @BindString, which binds an R.bool ID (or your specified type) to its corresponding field. 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
You can also perform binding on arbitrary objects by supplying your own view root. 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;
}
}
Another use is simplifying the view holder pattern inside of a list adapter. 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);
}
}
}
You can see this implementation in action in the provided sample. Calls to ButterKnife.bind can be made anywhere you would otherwise put findViewById calls. Other provided binding APIs: 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
You can group multiple views into a List or array. @BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
List<EditText> nameViews;
The apply method allows you to act on all the views in a list at once. ButterKnife.apply(nameViews, DISABLE);
ButterKnife.apply(nameViews, ENABLED, false);
Action and Setter interfaces allow specifying simple behavior. 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);
}
};
An Android Property can also be used with the apply method. ButterKnife.apply(nameViews, View.ALPHA, 0.0f);
LISTENER BINDING
Listeners can also automatically be configured onto methods. @OnClick(R.id.submit)
public void submit(View view) {
// TODO submit data to server...
}
All arguments to the listener method are optional. @OnClick(R.id.submit)
public void submit() {
// TODO submit data to server...
}
Define a specific type and it will automatically be cast. @OnClick(R.id.submit)
public void sayHi(Button button) {
button.setText("Hello!");
}
Specify multiple IDs in a single binding for common event handling. @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();
}
}
Custom views can bind to their own listeners by not specifying an ID. public class FancyButton extends Button {
@OnClick
public void onClick() {
// TODO do something!
}
}
BINDING RESET
Fragments have a different view lifecycle than activities. When binding a fragment in onCreateView, set the views to null in onDestroyView. Butter Knife returns an Unbinder instance when you call bind to do this for you. Call its unbind method in the appropriate lifecycle callback. 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
By default, both @Bind and listener bindings are required. An exception will be thrown if the target view cannot be found. To suppress this behavior and create an optional binding, add a @Nullable annotation to fields or the @Optional annotation to methods. Note: Any annotation named @Nullable can be used for fields. It is encouraged to use the @Nullable annotation from Android's "support-annotations" library. @Nullable @BindView(R.id.might_not_be_there) TextView mightNotBeThere; @Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {
// TODO ...
}
MULTI-METHOD LISTENERS
Method annotations whose corresponding listener has multiple callbacks can be used to bind to any one of them. Each annotation has a default callback that it binds to. Specify an alternate using the callback parameter. @OnItemSelected(R.id.list_view)
void onItemSelected(int position) {
// TODO ...
} @OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED)
void onNothingSelected() {
// TODO ...
}

ButterKnife官方使用例子的更多相关文章

  1. 官方 Animator 例子解析 Animator.MatchTarget

    一.官方的解释 Animator.MatchTargetSwitch to Manual ); Parameters matchPosition The position we want the bo ...

  2. 使用android-ndk官方ndkbuild例子

    Why this blog 现在(2018年9月27日),Android Studio中新建ndk项目都使用cmake而不是Android.mk+Application.mk的方式.但老项目需要维护, ...

  3. Java Restful框架:Jersey入门示例(官方例子)

    本文主要介绍了Java Restful框架Jersey入门例子(来源于官方网站https://jersey.java.net/),废话不多说进入正题. 在Jersey官方示例中(https://jer ...

  4. Shiro —— 从一个简单的例子开始

    一.Shiro是用来做权限的. 二.权限 1.基本概念: (1)安全实体:要保护的数据. (2)权限:是否有能力去操作(查看.修改.删除 )保护的数据. 2.权限的两个特性 (1)权限的继承性:A 包 ...

  5. emberjs学习一(环境和第一个例子)

    code { margin: 0; padding: 0; white-space: pre; border: none; background: transparent; } code, pre t ...

  6. cocos2d-x 3.2 例子文件工程的位置

    更新到3.2后突然想要看看官方的例子,忽然发现在test中的cpp工程下面没有了工程的启动配置.奇怪,难道只有代码吗?重新查找后原来启动的工程文件都移动到了build文件夹下面,具体的路径就是 coc ...

  7. web2py--------------用web2py写 django的例子 --------建立一个投票应用(3)

    我们建立了数据模型,然后这次来进行页面的展示 1.这里是列表页面的 control 这里是dal的语法 只有两行 第一行 是查询出所有问题,也就是问题的id大于0 第二行是返回问题的列表 这里是vie ...

  8. web2py--------------用web2py写 django的例子 --------开发环境

    我们先从广为人知的例子说起xi 也就是官方的例子,我会在最后给出代码: ============================环境=================== 编译器使用vs code , ...

  9. 【转】android官方侧滑菜单DrawerLayout详解

    原文网址:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/0925/1713.html drawerLayout是Support ...

随机推荐

  1. VC++2010组件安装失败解决办法

    安装SQLSERVER时,安装不上,总是报错说 VC++2010组件安装错误. 单独安装时,也会报出严重错误无法安装.就是下面这两个 最后到网上找到一个办法解决了:如下: 下载这个软件 Microso ...

  2. CF1139D Steps to One(DP,莫比乌斯反演,质因数分解)

    stm这是div2的D题……我要对不住我这个紫名了…… 题目链接:CF原网  洛谷 题目大意:有个一开始为空的序列.每次操作会往序列最后加一个 $1$ 到 $m$ 的随机整数.当整个序列的 $\gcd ...

  3. 基于配置文件的redis的主从复制

    redis中主从复制有很多种配置方法: 1. 使用配置文件即为redis.conf来配置 在随从redis中配置 # slaveof {masterHost} {MastePort} slaveof ...

  4. css预编译语言sass——mixin的使用

    以根据不同屏幕吃寸动态应用背景图片为例 新建一个mixin如下: @mixin bg_img($path, $ext){ @media screen and (max-device-width: 76 ...

  5. A1146. Topological Order

    This is a problem given in the Graduate Entrance Exam in 2018: Which of the following is NOT a topol ...

  6. 64位win8.1系统 运行 32位程序,文件夹路径是中文遇到问题

    今天有一位用户向我反应软件使用遇到问题. 用户使用的是64位win8.1系统,之前有很多用户使用64位的win8.1系统没遇到过问题. 远程协助了一下,差不多15分钟我试了几个办法没解决问题. 最后我 ...

  7. 关于MySQL索引的最左前缀匹配原则原理说明说明

    假设有2个这样的SQL SELECT * FROM table WHERE a = 1 AND c = 3; // c不走索引 SELECT * FROM table WHERE a = 1 AND ...

  8. PMP证书的获取,不知道10大注意事项会吃亏

    作为一个已经考过PMP的小项目经理我来说,近来接到不少咨询PMP的,有咨询考试事宜的,也有咨询后续的换审和PDU的,今天我这边就说说PMP项目管理证书要获取的一些注意事项,不注意的话可是会吃大亏的. ...

  9. HDU3974 Assign the task

    Assign the task Time Limit: 15000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  10. mongodb的sql日志

    在Yii2中是没有打印出mongodb的sql语句,故借用下log来查看吧. 在网上有说可以使用$model->find()->createCommand()->getRawSql( ...