ButterKnife官方介绍
2015-08-11 22:41
513 查看
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 { @Bind(R.id.title) TextView title; @Bind(R.id.subtitle) TextView subtitle; @Bind(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); }
NON-ACTIVITY BINDING
You can also perform binding on arbitrary objects by supplying your own view root.public class FancyFragment extends Fragment { @Bind(R.id.button1) Button button1; @Bind(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 { @Bind(R.id.title) TextView name; @Bind(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.
@Bind({ 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
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 in onCreateView,
set the views to
nullin
onDestroyView.
Butter Knife has an
unbindmethod to do this automatically.
public class FancyFragment extends Fragment { @Bind(R.id.button1) Button button1; @Bind(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; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } }
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 the
field or method.
Note: Any annotation named
@Nullablecan be used for this purpose. It is encouraged to use
the
@Nullableannotation from Android's "support-annotations" library, see Android
Tools Project.
@Nullable @Bind(R.id.might_not_be_there) TextView mightNotBeThere; @Nullable @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.
Download
ButterKnife JARThe source code to the library and sample application as well as this website is available on GitHub. The Javadoc is also available
to browse.
MAVEN
If you are using Maven for compilation you can declare the library as a dependency.<dependency> <groupId>com.jakewharton</groupId> <artifactId>butterknife</artifactId> <version>(insert latest version)</version> </dependency>
GRADLE
compile 'com.jakewharton:butterknife:(insert latest version)'
Be sure to suppress this lint warning in your
build.gradle.
lintOptions { disable 'InvalidPackage' }
Some configurations may also require additional exclusions.
packagingOptions { exclude 'META-INF/services/javax.annotation.processing.Processor' }
IDE CONFIGURATION
Some IDEs require additional configuration in order to enable annotation processing.IntelliJ IDEA — If your project uses an external configuration (like a Maven
pom.xml)
then annotation processing should just work. If not, try manual configuration.
Eclipse — Set up manual configuration.
PROGUARD
Butter Knife generates and uses classes dynamically which means that static analysis tools like ProGuard may think they are unused. In order to prevent them from being removed, explicitly mark them to be kept. To prevent ProGuard renaming classes that use @Bindon a member field the
keepclasseswithmembernamesoption is used.
-keep class butterknife.** { *; } -dontwarn butterknife.internal.** -keep class **$$ViewBinder { *; } -keepclasseswithmembernames class * { @butterknife.* <fields>; } -keepclasseswithmembernames class * { @butterknife.* <methods>; }
License
License
Copyright 2013 Jake WhartonLicensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
原文:http://jakewharton.github.io/butterknife/
相关文章推荐
- ASP.NET MVC+Bootstrap 实现短信验证
- Html(5)其他(缓存 及 js控制css)
- JavaScript 编程
- CSS3媒体查询入门,制作自己的响应式导航
- Html5(6)画图
- position relative 与 js 原生动画 浏览器兼容问题
- Html5(5)视频、音频 及 拖放
- JSP调用存储过程
- 剑指offer第31题 连续子数组最大和
- JS函数式编程【译】4.在Javascript中实现函数式编程的技术
- [leetcode-117]Populating Next Right Pointers in Each Node II(c++)
- javascript立即执行函数
- [持续更新]JavaScript学习笔记(一)
- [leetcode-116]Populating Next Right Pointers in Each Node(c++)
- XML解析、DOM解析、SAX解析、Json解析
- jquery的extend和fn.extend
- angular.equals方法
- 格式化html代码的函数有哪些
- javascript日期时间格式化
- CSS浮动相关解决办法