Android開發懶人庫 -- ButterKnife 用法


一、效果對比

今天推薦一個簡單易用的庫,這個開源庫可以讓我們從大量的findViewById()和setonclicktListener()解放出來,效果如圖如下:

這裏寫圖片描述

上圖的右鍵功能只能在AndroidStudio使用,Eclipse的小夥伴只能手打了。。


再看看以前的代碼,我們的那一系列findById是一個“浩大的工程”樣例如下

這是曾經一個項目的一個填童虎數據表單的一個Activity,這是一系列的聲明

public class UserInfoActivity extends Activity implements OnClickListener {
    TextView userNameTxt;
    RelativeLayout sexLayout;
    TextView sexTxt;
    RelativeLayout birthdayLayout;
    TextView birthdayTxt;
    RelativeLayout provinceLayout;
    TextView provinceTxt;
    RelativeLayout cityLayout;
    TextView cityTxt;
    RelativeLayout hasCarCardLayout;
    TextView hasCarCardTxt;
    RelativeLayout hasCarLayout;
    TextView hasCarTxt;
    RelativeLayout buyCarTimeLayout;
    TextView buyCarTimeTxt;
    RelativeLayout carBrandLayout;
    TextView carBrandTxt;
    RelativeLayout carTypeLayout;
    TextView carTypeTxt;
    RelativeLayout carPriceLayout;
    TextView carPriceTxt;
    RelativeLayout carCardNumLayout;
    TextView carCardNumTxt;
    RelativeLayout carNumLayout;
    TextView carNumTxt;
    RelativeLayout familyIncomeLayout;
    TextView familyIncomeTxt;
    RelativeLayout carCarImgLayout;
    ImageView carCarImg;
    RelativeLayout drivingLicenseLayout;
    ImageView drivingLicenseImg;
    LinearLayout backLin;
    LinearLayout saveBtn;

    RelativeLayout userNameLayout;
    LinearLayout sexLinLayout;
    LinearLayout birthdayLinLayout;
    LinearLayout provinceLinLayout;
    LinearLayout cityLinLayout;
    LinearLayout carCarLinLayout;
    LinearLayout hasCarLinLayout;
    LinearLayout buyCarTimeLinLayout;
    LinearLayout carBrandLinLayout;
    LinearLayout carTypeLinLayout;
    LinearLayout carPriceLinLayout;
    LinearLayout carCardNumLinLayout;
    LinearLayout carNumLinLayout;
    LinearLayout familiIncomeLinLayout;
    LinearLayout carCardImageLinLayout;
    LinearLayout drivindLicenseLinLayout;
    LinearLayout professionLinLayout;
    LinearLayout carInfoLayout;
    TextView professionTv;

這是一大堆的findById

    backLin = (LinearLayout) titleView.findViewById(R.id.backLin);
        saveBtn = (LinearLayout) titleView.findViewById(R.id.saveBtn);
        userNameLayout = (RelativeLayout) contentView
                .findViewById(R.id.userNameLayout);
        userNameTxt = (TextView) contentView.findViewById(R.id.userNameTxt);
        sexLayout = (RelativeLayout) contentView.findViewById(R.id.sexLayout);
        sexTxt = (TextView) contentView.findViewById(R.id.sexTxt);
        birthdayLayout = (RelativeLayout) contentView
                .findViewById(R.id.birthdayLayout);
        birthdayTxt = (TextView) contentView.findViewById(R.id.birthdayTxt);
        provinceLayout = (RelativeLayout) contentView
                .findViewById(R.id.provinceLayout);
        provinceTxt = (TextView) contentView.findViewById(R.id.provinceTxt);
        cityLayout = (RelativeLayout) contentView.findViewById(R.id.cityLayout);
        cityTxt = (TextView) contentView.findViewById(R.id.cityTxt);
        hasCarCardLayout = (RelativeLayout) contentView
                .findViewById(R.id.carCardLayout);
        hasCarCardTxt = (TextView) contentView.findViewById(R.id.carCardTxt);
        hasCarLayout = (RelativeLayout) contentView
                .findViewById(R.id.hasCarLayout);
        hasCarTxt = (TextView) contentView.findViewById(R.id.hasCarTxt);
        buyCarTimeLayout = (RelativeLayout) contentView
                .findViewById(R.id.buyCarTimeLayout);
        buyCarTimeTxt = (TextView) contentView.findViewById(R.id.buyCarTimeTxt);
        carBrandLayout = (RelativeLayout) contentView
                .findViewById(R.id.carBrandLayout);
        carBrandTxt = (TextView) contentView.findViewById(R.id.carBrandTxt);
        carTypeLayout = (RelativeLayout) contentView
                .findViewById(R.id.carTypeLayout);
        carTypeTxt = (TextView) contentView.findViewById(R.id.carTypeTxt);
        carPriceLayout = (RelativeLayout) contentView
                .findViewById(R.id.carPriceLayout);
        carPriceTxt = (TextView) contentView.findViewById(R.id.carPriceTxt);
        carCardNumLayout = (RelativeLayout) contentView
                .findViewById(R.id.carCardNumLayout);
        carCardNumTxt = (TextView) contentView.findViewById(R.id.carCardNumTxt);
        carNumLayout = (RelativeLayout) contentView
                .findViewById(R.id.carNumLayout);
        carNumTxt = (TextView) contentView.findViewById(R.id.carNumTxt);
        familyIncomeLayout = (RelativeLayout) contentView
                .findViewById(R.id.familyIncomeLayout);
        familyIncomeTxt = (TextView) contentView
                .findViewById(R.id.familyIncomeTxt);
        carCarImgLayout = (RelativeLayout) contentView
                .findViewById(R.id.carCarImgLayout);
        carCarImg = (ImageView) contentView.findViewById(R.id.carCarImg);
        drivingLicenseLayout = (RelativeLayout) contentView
                .findViewById(R.id.drivingLicenseLayout);
        drivingLicenseImg = (ImageView) contentView
                .findViewById(R.id.drivingLicenseImg);

        sexLinLayout = (LinearLayout) contentView
                .findViewById(R.id.sexLinLayout);
        birthdayLinLayout = (LinearLayout) contentView
                .findViewById(R.id.birthdayLinLayout);
        provinceLinLayout = (LinearLayout) contentView
                .findViewById(R.id.provinceLinLayout);
        cityLinLayout = (LinearLayout) contentView
                .findViewById(R.id.cityLinLayout);
        carCarLinLayout = (LinearLayout) contentView
                .findViewById(R.id.carCarLinLayout);
        hasCarLinLayout = (LinearLayout) contentView
                .findViewById(R.id.hasCarLinLayout);
        buyCarTimeLinLayout = (LinearLayout) contentView
                .findViewById(R.id.buyCarTimeLinLayout);
        carBrandLinLayout = (LinearLayout) contentView
                .findViewById(R.id.carBrandLinLayout);
        carTypeLinLayout = (LinearLayout) contentView
                .findViewById(R.id.carTypeLinLayout);
        carPriceLinLayout = (LinearLayout) contentView
                .findViewById(R.id.carPriceLinLayout);
        carCardNumLinLayout = (LinearLayout) contentView
                .findViewById(R.id.carCardNumLinLayout);
        carNumLinLayout = (LinearLayout) contentView
                .findViewById(R.id.carNumLinLayout);
        familiIncomeLinLayout = (LinearLayout) contentView
                .findViewById(R.id.familiIncomeLinLayout);
        drivindLicenseLinLayout = (LinearLayout) contentView
                .findViewById(R.id.drivindLicenseLinLayout);
        carCardImageLinLayout = (LinearLayout) contentView
                .findViewById(R.id.carCardImageLinLayout);
        professionLinLayout = (LinearLayout) contentView
                .findViewById(R.id.professionLinLayout);
        carInfoLayout = (LinearLayout) contentView
                .findViewById(R.id.carInfoLayout);
        professionTv = (TextView) contentView.findViewById(R.id.professionTv);

看着看着蛋都碎了,簡直不能忍


二、butterknife導入和使用

1.下載導入開源庫,github地址:https://github.com/JakeWharton/butterknife

2.Android studio安裝插件:
Android Studio: go to Preferences → Plugins → 搜索“ButterKnife Zelezny”,沒有的話點擊“Browse” ,然後安裝插件

好,廢話不多,開始拆作者的樣例(樓主小學英文大致的理解講述下):

Annotate fields with @Bind and a view ID for Butter Knife to find and automatically cast the corresponding view in your layout.
註釋字段“綁定”和“ Butter Knife”的視圖標識,並自動在佈局中查看相應的視圖。

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

分析:使用 @Bind 就可以對控件進行聲明,已經findViewById的操作,然後在onCreate()方法中調用 ButterKnife.bind(this);使之生效,如果你覺得有必要的話可以在onDestory()方法中再調用ButterKnife.unbind(this);進行解綁操作

You can also perform binding on arbitrary objects by supplying your own view root.
可以通過提供您自己的視圖根試圖來執行任意對象的綁定。我們可以用在fragment等用到inflater的地方。

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

分析:這邊與Activity的差別只是在調用的方法中需要傳入被綁定的那個根試圖而已。

Another use is simplifying the view holder pattern inside of a list adapter.
在ListView或者其他一些用到 ViewHolder形式的地方都可以用

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 group multiple views into a List or array
可以把一些控件放進一個集合或者數組中

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

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.
指定多個身ID在一個單一的綁定事件處理。

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

三、butterknife文檔

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 {
  @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. Callingbind 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 {
  @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.bind can be made anywhere you would otherwise putfindViewById 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 withButterKnife.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 theonFinishInflate() callback.

View Lists

You can group multiple views into a List or 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 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 has anunbind method 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 @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 the field or method.

Note: Any annotation named @Nullable can be used for this purpose. It is encouraged to use the@Nullable annotation from Android's "support-annotations" library, seeAndroid 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 thecallback 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 aView, 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.

Download

Butter Knife 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>(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.

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


-keep class butterknife.** { *; }
-dontwarn butterknife.internal.**
-keep class **$$ViewBinder { *; }

-keepclasseswithmembernames class * {
    @butterknife.* <fields>;
}

-keepclasseswithmembernames class * {
    @butterknife.* <methods>;
}

博客參考:王亟亟的大牛之路

文檔原文地址:http://jakewharton.github.io/butterknife/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章