Butter Knife

1.Butter Knife fuction

Field and method binding for Android views

2.Link

http://jakewharton.github.io/butterknife/

3.Introduction

Annotate fields with @Bind 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 inonCreateView,
set the views to null in onDestroyView.
Butter Knife returns an Unbinderinstance 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 ...
}

BONUS

Also included are findById methods 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.findById and enjoy even more fun.

4. Android ButterKnife Zelezny

Simple plug-in for Android Studio/IDEA that allows one-click creation of Butterknife view
injections.

How to install

  • in Android Studio: go to Preferences → Plugins → Browse repositories and search for ButterKnife
    Zelezny

or

  • download it and install via Preferences
    → Plugins → Install plugin from disk

How to use it

  1. Make sure you have latest Butterknife lib on your classpath
  2. Right click on usage of desired layout reference (e.g. R.layout.main in your Activity or Fragment), then Generate andGenerate
    ButterKnife Injections
  3. Pick injections you want, you also have an option to create ViewHolder for adapters.
  4. Click Confirm and 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 using
  • Make sure you have Butterknife on your classpath
  • Make sure that your cursor is on layout file in Activity on Fragment

Why ‘Zelezny‘?

Jan ?elezny 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.

时间: 2024-11-05 13:04:05

Butter Knife的相关文章

Butter Knife使用详解

转载请注明出处:http://www.cnblogs.com/cnwutianhao/p/6610529.html Butter Knife Github地址: https://github.com/JakeWharton/butterknife 官方说明给出的解释是 Bind Android views and callbacks to fields and methods. Field and method binding for Android views which uses annot

【Butter Knife】依赖注入方式简化代码提高开发效率

Butter Knife是一款非常不错的开源框架,其目的是简化代码,提高项目的开发效率. 以往的开发我们经常需要用findViewById(R.xx.xxx);几乎没个页面都会涉及到,无论Activity还是Fragment甚至listView.GridView中的 Adapter.这些重复性的代码会让人觉得很枯燥,因为闭上眼都不会敲错的代码,每天重复几百遍是有点耗时,尽管有代码提示.而且可能会因为不同field的忘记书写而导致NullPoint空指针. 那么还是直接进入主题: 步骤: 第三方框

Butter Knife 使用方法

获取控件 @InjectView(R.id.image_show_password)ImageView image_show_password; 控件事件 @OnClick(R.id.btn_submit) void btn_submit(){ intent=new Intent(context, MobileValidation.class); startActivity(intent);  } 配置项目 选择项目属性 选择 Java Compiler->选择 anotaion process

[轉]Android Libraries 介紹 - Butter knife

原文地址 Butter Knife 簡介 Butter Knife - Field and method binding for Android views.助你簡化程式碼,方便閱讀. 使用方法 開發 andriod app 的時候,一定有寫過類似的 code: class ExampleActivity extends Activity { TextView title; TextView subtitle; TextView footer; @Override public void onC

Butter Knife:一个安卓视图注入框架

2014年5月8日 星期四 14:52 官网: http://jakewharton.github.io/butterknife/ GitHub地址: https://github.com/JakeWharton/butterknife JavaDocs地址: http://jakewharton.github.io/butterknife/javadoc/ 注:本随笔翻译自官网,做了一些整理和注释.来自我的OneNote笔记 大纲: @InjectView (Activity,Fragment

android注解[Jake Wharton Butter Knife]

Introduction Annotate fields with @InjectView and 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.subti

Android RoboGuice开源框架、Butter Knife开源框架浅析

Google Guice on Android(RoboGuice) 今天介绍一下Google的这个开源框架RoboGuice, 它的作用跟之前讲过的Dagger框架差点儿是一样的,仅仅是Dagger比它的功能更强大一些. Dagger通过专注于一种简化的功能集以一种不同的方式达到了更好的性能.有人觉得RoboGuice节约了大量的时间.较少的代码意味着较少的错误.较少的样板代码意味着能够把很多其它的时间放到应用的核心逻辑上.所以这就是为什么我们要使用这些开源框架来开发的原因. 以下我们来说说R

Butter Knife的使用(仅限Android Studio)

四月,五月是比之前忙了很多,明白了很多,也改变来了很多,今天依旧在被迫加班,手头的工作都做的差不多了,想想已经很久没有学习过新的知识了.人懒又笨,但是也不想辜负朋友的一番好意,Butter Knife就是朋友介绍的比较好用的类库.今天用了一下还是很好用虽然和XUtils的注解很相识,但是呢如果项目中的网络请求没有使用XUtils,就可以使用它了,想说它的使用方法真的很简单,一切了解一下吧. 配置: 用gradle配置的时候加入: compile 'com.jakewharton:butterkn

豆瓣App中用到的一些框架

1.Google Gsonhttps://code.google.com/p/google-gson/ 2.httpmimehttp://hc.apache.org/ 3.Commons IOhttp://commons.apache.org/proper/commons-io 4.Android Nexthttps://github.com/mcxiaoke/Android-Next 5.Butter Knifehttps://github.com/JakeWharton/butterknif