Introduction

Annotate fields with@InjectViewand a view ID for Butter Knife to find and automatically cast the corresponding view in your layout.

class ExampleActivity extends Activity { @InjectView(R.id.title) TextView title; @InjectView(R.id.subtitle) TextView subtitle; @InjectView(R.id.footer) TextView footer; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); ButterKnife.inject(this); // TODO Use "injected" views... } }

Instead of slow reflection, code is generated to perform the view look-ups. Callinginjectdelegates 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 inject(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 INJECTION

You can also perform injection on arbitrary objects by supplying your own view root.

public class FancyFragment extends Fragment { @InjectView(R.id.button1) Button button1; @InjectView(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.inject(this, view); // TODO Use "injected" views... 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 { @InjectView(R.id.title) TextView name; @InjectView(R.id.job_title) TextView jobTitle; public ViewHolder(View view) { ButterKnife.inject(this, view); } } }

You can see this implementation in action in the provided sample.

Calls toButterKnife.injectcan be made anywhere you would otherwise putfindViewByIdcalls.

Other provided injection APIs:

  • Inject arbitrary objects using an activity as the view root. If you use a pattern like MVC you can inject the controller using its activity withButterKnife.inject(this, activity).
  • Inject a view's children into fields usingButterKnife.inject(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 theonFinishInflate()callback.

VIEW LISTS

You can group multiple views into aListor array.

@InjectViews({ R.id.first_name, R.id.middle_name, R.id.last_name }) List<EditText> nameViews;

Theapplymethod allows you to act on all the views in a list at once.

ButterKnife.apply(nameViews, DISABLE); ButterKnife.apply(nameViews, ENABLED, false);

ActionandSetterinterfaces allow specifying simple behavior.

static final Action<View> DISABLE = new Action<>() { @Override public void apply(View view, int index) { view.setEnabled(false); } } static final Setter<View, Boolean> ENABLED = new Setter<>() { @Override public void set(View view, Boolean value, int index) { view.setEnabled(value); } }

An AndroidPropertycan also be used with theapplymethod.

ButterKnife.apply(nameViews, View.ALPHA, 0);

LISTENER INJECTION

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! } }

INJECTION RESET

Fragments have a different view lifecycle than activities. When injecting a fragment inonCreateView, set the views tonullinonDestroyView. Butter Knife has aresetmethod to do this automatically.

public class FancyFragment extends Fragment { @InjectView(R.id.button1) Button button1; @InjectView(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.inject(this, view); // TODO Use "injected" views... return view; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.reset(this); } }

OPTIONAL INJECTIONS

By default, both@InjectViewand listener injections are required. An exception will be thrown if the target view cannot be found.

To suppress this behavior and create an optional injection, add the@Optionalannotation to the field or method.

@Optional @InjectView(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 thecallbackparameter.

@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 arefindByIdmethods which simplify code that still has to find views on aView,Activity, orDialog. 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 forButterKnife.findByIdand enjoy even more fun.

Download

Butter Knife v6.1.0 JAR

The source code to the library and sample application as well as this website isavailable on GitHub. The Javadoc is alsoavailable 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>6.1.0</version> </dependency>

GRADLE

compile 'com.jakewharton:butterknife:6.1.0'

Be sure to supress this lint warning in yourbuild.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 Mavenpom.xml) then annotation processing should just work. If not, trymanual configuration.
  • Eclipse— Set upmanual 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 @InjectView on a member field thekeepclasseswithmembernamesoption is used.

-keep class butterknife.** { *; }-dontwarn butterknife.internal.**-keep class **$$ViewInjector { *; }-keepclasseswithmembernames class * {    @butterknife.* <fields>;}-keepclasseswithmembernames class * {    @butterknife.* <methods>;}

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.0Unless required by applicable law or agreed to in writing, softwaredistributed 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 andlimitations under the License.

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. Android之旅第一站——初识安卓…
  2. Android设计应用图标不用愁---Asset Stud
  3. 如何下载并编译Android4.0内核源码goldfi
  4. Android各版本 内外卡真实路径
  5. Android 实时视频采集/编码/传输/解码/播
  6. android中使用jni,ndk的C语言回调方法
  7. [Android] 一份代码,两个版本
  8. 一行代码搞定Android屏幕适配
  9. Android系统架构的简单描述
  10. Android(安卓)R文件消失