Butter Knife
2016-05-11 10:13
507 查看
1.Butter Knife fuction
Field and method binding for Android views2.Link
http://jakewharton.github.io/butterknife/3.Introduction
Annotate fields with@Bindand 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
binddelegates
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.boolID (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.bindcan be made anywhere you would otherwise put
findViewByIdcalls.
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 Listor array.
@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name }) List<EditText> nameViews;
The
applymethod allows you to act on all the views in a list at once.
ButterKnife.apply(nameViews, DISABLE); ButterKnife.apply(nameViews, ENABLED, false);
Actionand
Setterinterfaces
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
Propertycan
also be used with the
applymethod.
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 inonCreateView,
set the views to
nullin
onDestroyView.
Butter Knife returns an
Unbinderinstance when you call
bindto
do this for you. Call its
unbindmethod 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 @Bindand 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
@Nullableannotation
to fields or the
@Optionalannotation to methods.
Note: Any annotation named
@Nullablecan be used for fields. It is encouraged
to use the
@Nullableannotation 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 callbackparameter.
@OnItemSelected(R.id.list_view) void onItemSelected(int position) { // TODO ... } @OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED) void onNothingSelected() { // TODO ... }
BONUS
Also included are findByIdmethods which simplify code that still has to find
views on a
View,
Activity,
or
Dialog. It uses generics to infer the return type and automatically performs
the cast.
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);
Add a static import for
ButterKnife.findByIdand enjoy even more fun.
4. Android ButterKnife Zelezny
Simple plug-in for Android Studio/IDEA that allows one-click creation of Butterknife viewinjections.
How to install
in Android Studio: go to Preferences → Plugins → Browse repositoriesand search for
ButterKnife Zelezny
or
download it and install via
Preferences → Plugins → Install plugin from disk
How to use it
Make sure you have latest Butterknife lib on your classpath
Right click on usage of desired layout reference (e.g. R.layout.main in your Activity or Fragment), then
Generateand
Generate ButterKnife Injections
Pick injections you want, you also have an option to create ViewHolder for adapters.
Click
Confirmand enjoy injections in your code with no work!
Contributing
Pull requests are welcomed!make sure you stick to our coding
style.
follow Getting Started with Plugin
Development
make sure you have Java 6 installed if you want to publish it in the plugin repository
initial project setup might be tricky (like editing iml files manually), don't hesitate to contact @destil if
you run into troubles.
Common issue: The plugin is not working after I updated to new Android Studio
AS promts you to update plugins after update, you need to update them before usingMake sure you have Butterknife on your classpath
Make sure that your cursor is on layout file in Activity on Fragment
Why 'Zelezny'?
Jan Železný is a famous Czech javelin thrower, Olympic champion and world record
holder. With Zelezny's javelin, your butter knife will be much sharper!
See our other Czech personalities who help with #AndroidDev.
相关文章推荐
- jQuery学习和知识点总结归纳
- js中基本操作
- css定义超级链接a标签里面的title的样式
- zyUpload界面绝佳、体验超棒的HTML5上传插件
- IOS端 微信 safari chrome 的jQuery on delegate 事件无效
- javascript基础(1)
- js读取并解析excel文件,之后上传json到服务器
- 自定义复选框、单选按钮外观方法。支持IE、Firefox、chrome
- bootstrap 简单教程
- [NodeJS]Jenkins-cli
- [JS]HTML中把图片划分成多个作用区域的区域标记
- jquery attr与prop 的区别
- jQuery的框架介绍
- html5 postMessage解决跨域、跨窗口消息传递
- 289. Game of Life
- 前端js干货
- jQuery链式调用与show知识浅析
- 与h5交互
- Hadoop2源码分析-HDFS datanode核心模块分析
- 利用PopupWindow做出仿IOS样式的选择器