Android开发懒人库 -- ButterKnife 用法

来源:互联网 发布:linux 发送arp请求 编辑:程序博客网 时间:2024/05/16 08:30


一、效果对比

今天推荐一个简单易用的库,这个开源库可以让我们从大量的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 anR.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 tonull 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.

  • 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 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 @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/

0 0
原创粉丝点击