Android框架式编程之BufferKnife

Android 开发过程中,我们需要写大量的findViewById()和setonclicktListener()等事件, 那么现在有一个框架可以很好的解决这个问题 ---- BufferKnife。BufferKnife可以大量精简代码,而且不影响性能,可以通过查看Butter Knife了解到,其自定义注解的实现都是限定为RetentionPolicy.CLASS,也就是到编译出.class文件为止有效,在运行时不会额外消耗性能。

下面是说明一下如何使用Butter Knife :

基本的使用方法如下:

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); // 必须在设置好布局事件后绑定当前的Activity
    // TODO Use fields...
  }
}

上面的慢反射代码执行下来生成的class代码如下:

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

另外Butter Knife 也可以用于资源绑定:

可以使用@BindBool@BindColor@BindDimen@BindDrawable@BindInt@BindString来预绑定一些资源到对应的字段。

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

那么有人会问,非Activity的类如何绑定呢?其实只需要比Activity绑定时多传递一个参数即可,即根View:

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

Butter Knife 还有另一个用途就是简化List的Adapter的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 {
    @BindView(R.id.title) TextView name;
    @BindView(R.id.job_title) TextView jobTitle;

    public ViewHolder(View view) {
      ButterKnife.bind(this, view);
    }
  }
}

基本上你想调用findViewById的方法的地方应该都是可以设置ButterKnife.bind的。

使用ButterKnife.bind(这)将视图的孩子绑定到字段中。 如果您在布局中使用<merge>标签,并在自定义视图构造函数中展开,则可以立即调用它。 或者,从XML扩展的自定义视图类型可以在onFinishInflate()回调中使用它。

提供的其他的绑定的APIs:

  • 使用Activity作为视图根来绑定任意对象。如果你使用类似MVC 的模式,你可以使用ButterKnife.bind(this, activity)来绑定控制器。

ButterKnife还可以处理View Lists:

你可以将多个view分组到列表或者数组:

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 in onCreateView, 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 ViewActivity, 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

Gradle

compile ‘com.jakewharton:butterknife:(insert latest version)‘
annotationProcessor ‘com.jakewharton:butterknife-compiler:(insert latest version)
时间: 2024-08-29 12:46:30

Android框架式编程之BufferKnife的相关文章

Android框架式编程之Retrofit

一.Retrofit 简介 Retrofit 官网地址: https://github.com/square/retrofit Retrofit(即Retrofit,目前最新版本为2.6.0版本),是目前非常流行的网络请求框架,底层是基于okHttp实现的.准确来说Retrofit是对okHttp的进一步封装,它功能强大,支持同步和异步,支持多种数据的解析方式(默认为Gson),支持RxJava. Retrofit 最大的优势就是简洁易用,它通过注解配置网络请求的参数,采用大量的设计模式来简化我

Android框架式编程之EasyPermissions

EasyPermission库是一个谷歌官方提供的简化基本的系统权限逻辑的库,可用于在Android M或者更高版本上. 官方项目地址:https://github.com/googlesamples/easypermissions 一.EasyPermission配置依赖 在需要使用此库的module的build.gradle中添加以下代码: dependencies { // For developers using AndroidX in their applications    imp

Android实践--Android Http 客户端编程之GET

Android Http 客户端编程之GET 说起Http编程,不尽然想起GET和POST两种请求方式,本文以简洁明了的的步骤和说明,将Android中常用的Http编程的方式列举出来,给刚刚在Android路上起步的奋斗者参考和指引,希望快速上手应用Android Http编程的同仁可以先绕过下面一段话. 做一件事之前,我们是否能驻足想一下要做这件事,我们需要做哪些工作,然后在经验中积累出模板思路和步骤,在程序界通常用设计模式来概括这些工作良好的解决方案.有了这些总结积累,这样我们就能举一反三

Android实践--Http 客户端编程之GET请求

Android Http 客户端编程之GET 说起Http编程,不尽然想起GET和POST两种请求方式,本文以简洁明了的的步骤和说明,将Android中常用的Http编程的方式列举出来,给刚刚在Android路上起步的奋斗者参考和指引,希望快速上手应用Android Http编程的同仁可以先绕过下面一段话. 做一件事之前,我们是否能驻足想一下要做这件事,我们需要做哪些工作,然后在经验中积累出模板思路和步骤,在程序界通常用设计模式来概括这些工作良好的解决方案.有了这些总结积累,这样我们就能举一反三

Android编程之Fragment动画加载方法源码详解

上次谈到了Fragment动画加载的异常问题,今天再聊聊它的动画加载loadAnimation的实现源代码: Animation loadAnimation(Fragment fragment, int transit, boolean enter, int transitionStyle) { 接下来具体看一下里面的源码部分,我将一部分一部分的讲解,首先是: Animation animObj = fragment.onCreateAnimation(transit, enter, fragm

Android编程之Fragment使用动画造成Unknown animation name: objectAnimator异常

在为Fragment做切换动画,启动后遇到了一个异常: Caused by: java.lang.RuntimeException: Unknown animation name: objectAnimator 截图如下: 我的代码如下: fragment = Fragment.instantiate(getActivity(), clz.getName()); fragment.setArguments(args); ft.setCustomAnimations(R.animator.frag

Android多线程编程之Handler篇(消息机制)

Android多线程编程之Handler篇(消息机制) Android的消息机制主要是指Handler的运行机制,Handler的运行需要底层的MessageQueue和Looper的支撑. MessageQueue 消息队列,以队列的形式(实为单链表结构)对外提供插入和删除的工作, Looper 以无限循环的形式不断获取MessageQueue中的消息,有则处理,无则等待. ThreadLocal ThreadLocal可以在不同的线程互不干扰的存储并提供数据,通过ThreadLocal可以很

Android编程之LayoutInflater的inflate方法实例

假设你不关心其内部实现,仅仅看怎样使用的话,直接看这篇就可以. 接上篇,接下来,就用最最简单的样例来说明一下: 用两个布局文件main 和 test: 当中,main.xml文件为: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layo

android网络编程之pull解析xml

android网络编程之pull解析xml 除了前面介绍过的SAX以及DOM方法,还可以通过Pull对xml文档进行一个解析.Pull解析器的解析方式与SAX非常相似.它提供了类似的事件,使用parser.next()可以进入下一元素并触发相应事件,事件将作为数值代码被发送,因此可以使用一个switch对感兴趣的事件进行选择,然后进行相应的处理,调用parser.nextText()方法可以获取下一个Text类型元素的值. pull解析器特点: *结构简单:一个接口.一个例外.一个工厂就组成了P