ButterKnife官方使用例子
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官方使用例子的更多相关文章
- 官方 Animator 例子解析 Animator.MatchTarget
一.官方的解释 Animator.MatchTargetSwitch to Manual ); Parameters matchPosition The position we want the bo ...
- 使用android-ndk官方ndkbuild例子
Why this blog 现在(2018年9月27日),Android Studio中新建ndk项目都使用cmake而不是Android.mk+Application.mk的方式.但老项目需要维护, ...
- Java Restful框架:Jersey入门示例(官方例子)
本文主要介绍了Java Restful框架Jersey入门例子(来源于官方网站https://jersey.java.net/),废话不多说进入正题. 在Jersey官方示例中(https://jer ...
- Shiro —— 从一个简单的例子开始
一.Shiro是用来做权限的. 二.权限 1.基本概念: (1)安全实体:要保护的数据. (2)权限:是否有能力去操作(查看.修改.删除 )保护的数据. 2.权限的两个特性 (1)权限的继承性:A 包 ...
- emberjs学习一(环境和第一个例子)
code { margin: 0; padding: 0; white-space: pre; border: none; background: transparent; } code, pre t ...
- cocos2d-x 3.2 例子文件工程的位置
更新到3.2后突然想要看看官方的例子,忽然发现在test中的cpp工程下面没有了工程的启动配置.奇怪,难道只有代码吗?重新查找后原来启动的工程文件都移动到了build文件夹下面,具体的路径就是 coc ...
- web2py--------------用web2py写 django的例子 --------建立一个投票应用(3)
我们建立了数据模型,然后这次来进行页面的展示 1.这里是列表页面的 control 这里是dal的语法 只有两行 第一行 是查询出所有问题,也就是问题的id大于0 第二行是返回问题的列表 这里是vie ...
- web2py--------------用web2py写 django的例子 --------开发环境
我们先从广为人知的例子说起xi 也就是官方的例子,我会在最后给出代码: ============================环境=================== 编译器使用vs code , ...
- 【转】android官方侧滑菜单DrawerLayout详解
原文网址:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/0925/1713.html drawerLayout是Support ...
随机推荐
- [HEOI2016/TJOI2016]游戏 解题报告
[HEOI2016/TJOI2016]游戏 看起来就是个二分图匹配啊 最大化匹配是在最大化边数,那么一条边就代表选中一个坐标内的点 但是每一行不一定只会有一个匹配 于是把点拆开,按照'#'划分一下就好 ...
- 阶乘函数(factorial)——结果在整型范围内的阶乘计算
定义: 在数学中,正整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,计为n!,例如5的阶乘计为5!,其值为120: \[ 5!=5\times 4\times 3\times ...
- mysql json 使用 类型 查询 函数
一,对记录的操作 1.创建有json字段的表 -- 创建表 ) , info JSON); 2.插入记录 -- 插入含有json数组的记录 , , "abc", NULL, TRU ...
- vue学习笔记(二)- 数据绑定、列表渲染、条件判断
vue的数据绑定和列表渲染的造轮子 GitHub:八至 作者:狐狸家的鱼 双向数据绑定 Vue中数据的双向绑定-v-model 数据->页面 页面->数据 适用:input.select. ...
- 论一个蒟蒻的脑子里可以有多少坑(貌似咕了……目前更新保持在noip阶段)
就是错题整理了,其实也会把一些不该犯的失误整进来. 其实之前一直拖着不想写,直到某次模拟赛,看错了2道题,顺便爆了一道题的int(没错第一个点就会爆)之后爆零了,吓得我赶紧把这篇博客搞出来了..... ...
- LOJ#2542 随机游走
解:首先minmax容斥变成经过集合t的第一个点就停止的期望步数.对于某个t,设从x开始的期望步数为f(x) 如果x∈t,f(x) = 0.否则f(x) = ∑f(y) / in[x] + 1 树上高 ...
- django orm 重点大全
1.最简单的跨表,查询外键表中符合主表条件的记录列表 #用户类型表 class User_typ(models.Model): name=models.CharField(max_length=32) ...
- Linux批量修改(删除)文件名某些字符(rename命令)
假设在路径C:/下存在多个类似以下的文件名 file_nall_abc1.txt file_nall_abc2.txt file_nall_abc3.txt file_nall_abc4.txt fi ...
- TODO java疑问
TODOjava 疑惑-关于方法调用的参数是基本类型和引用类型的差别 class DataWrap { int a; int b; } public class ReferenceTransferTe ...
- PHP工厂方法模式
此模式中,通过定义一个抽象的核心工厂类,并定义创建产品对象的接口,创建具体产品实例的工作延迟到其工厂子类去完成.这样做的好处是核心类只关注工厂类的接口定义,而具体的产品实例交给具体的工厂子类去创建.当 ...