Butter Knife

View "injection" library for Android

Introduction

Android developers, like most developers, are lazy and do not want to write a bunch of code which looks like this:

class ExampleActivity extends Activity {
  TextView title;
  TextView subtitle;
  TextView footer;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    title = (TextView) findViewById(R.id.title);
    subtitle = (TextView) findViewById(R.id.subtitle);
    footer = (TextView) findViewById(R.id.footer);

    // TODO Use views...
  }
}

Instead, they turn to helper libraries that they likely do not fully understand. These libraries might use annotations and magic to allow you to condense your code to:

class ExampleActivity extends Activity {
  @Magic(R.id.title) TextView title;
  @Magic(R.id.subtitle) TextView subtitle;
  @Magic(R.id.footer) TextView footer;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    // TODO Use "injected" views...
  }
}

While it looks pretty, magic is for children (and it also comes with a heavy runtime penalty).

Instead we can leverage a powerful part of the javac compiler to generate the first example's findViewById boilerplate while still allowing us to keep the terseness of the annotations:

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);
    Views.inject(this);
    // TODO Use "injected" views...
  }
}

In place of magic we now call an inject method. This method delegates to generated code that you can see and debug:

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);
}

Some people call this view injection and lump it along with traditional dependency injection frameworks. They may be wrong in nomenclature, but perhaps there exists some use for it.

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 View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fancy_fragment, container, false);
    Views.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 convertView;
  }

  static class ViewHolder {
    @InjectView(R.id.title) TextView name;
    @InjectView(R.id.job_title) TextView jobTitle;

    public ViewHolder(View view) {
      Views.inject(this, view);
    }
  }
}

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

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 with Views.inject(this, activity).
  • Inject a view's children into fields using Views.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 the onLayoutInflated() callback.

Click Listener Injection

Click listeners can also automatically be configured onto methods.

@OnClick(R.id.submit)
public void submit() {
  // TODO submit data to server...
}

You can add the view as an argument to the method. 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();
  }
}

Injection Reset

Fragments have a different view lifecycle than activities. When injecting a fragment in onCreateView, set the views to null in onDestroyView. Butter Knife has a reset method to do this automatically.

public class FancyFragment extends Fragment {
  @InjectView(R.id.button1) Button button1;
  @InjectView(R.id.button2) Button button2;

  @Override View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fancy_fragment, container, false);
    Views.inject(this, view);
    // TODO Use "injected" views...
    return view;
  }

  @Override void onDestroyView() {
    super.onDestroyView();
    Views.reset(this);
  }
}

Optional Injections

By default, both @InjectView and @OnClick 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 @Optional annotation to the field or method.

@Optional @InjectView(R.id.might_not_be_there) TextView mightNotBeThere;

@Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {
  // TODO ...
}

Bonus

Also included are two findById methods which simplify code that still has to find views on a View or Activity. 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 = Views.findById(view, R.id.first_name);
TextView lastName = Views.findById(view, R.id.last_name);
ImageView photo = Views.findById(view, R.id.photo);

Add a static import for Views.findById and enjoy even more fun.

Download

Butter Knife JAR

The source code to the library and sample application as well as this website is available on GitHub.

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>

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 @InjectView on a member field the keepnames option is used.

-dontwarn butterknife.internal.**
-keep class **$$ViewInjector { *; }
-keepnames class * { @butterknife.InjectView *;}

License

Copyright 2013 Jake Wharton

Licensed 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.
Fork me on GitHub