天天看点

Android Butter Knife使用详解

    • 1. 简介
    • 2. 使用场景代码示例
      • 2.1 Activity下使用Butter Knife
      • 2.2 资源类绑定
      • 2.3 非Activity场景——Fragment中绑定
      • 2.4 非Activity场景——Adapter中绑定
      • 2.5 其他特性
      • 2.6 监听器绑定
      • 2.7 重置绑定
      • 2.8 可选绑定
      • 2.9 对包含多个监听方法的绑定——ListView OnItemSelectedListener
      • 2.10 Butter Knife简单findById方法
    • 3. Android Studio的插件——Android ButterKnife Zelezny

1. 简介

Butter Knife是一种View注解框架,可以大量减少模板类代码的书写,极大简化了类似findViewById 和OnClickedListener等View相关的代码。Butter Knife使用的java annotation Process技术实现,即在代码编译阶段就已经解析了注解内容并生成了模板代码,不会影响代码运行阶段的性能。

Butter Knife最新版本为8.x, 官方代码托管在gitHub上,代码地址如下:

https://github.com/JakeWharton/butterknife

该库的License是Apache License 2.0

2. 使用场景代码示例

对一个成员变量使用@BindView注解,并传入一个View ID, ButterKnife 就能够帮你找到对应的View, 并自动的进行转换, 与缓慢的反射相比,Butter Knife 使用再编译时生成的代码来执行View的查找, 因此不必担心注解的性能问题。调用bind来生成这些代码,你可以查看或调试这些代码。

要使用Butter Knife首先需要在 app Module下的build.gradle下引入相关的依赖库

# 注解库
implementation 'com.jakewharton:butterknife:8.8.1'
#编译库
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
           

2.1 Activity下使用Butter Knife

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

    //绑定多个View
    @BindViews({R.id.link_enterprise_text, R.id.link_enterprise_table,R.id.enterprise_sign,
            R.id.enterprise_manager})
    List<TextView> enterpriseInfoList;

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_activity);
        ButterKnife.bind(this);
        // TODO Use fields...
    }
}
           

2.2 资源类绑定

绑定资源到类成员上可以使用@BindBool、@BindColor、@BindDimen、@BindDrawable、@BindInt、@BindString。使用时对应的注解需要传入对应的id资源,例如@BindString你需要传入R.string.id_string的字符串的资源id。

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

2.3 非Activity场景——Fragment中绑定

Butter Knife提供了bind的几个重载,只要传入跟布局,便可以在任何对象中使用注解绑定。

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

2.4 非Activity场景——Adapter中绑定

在ListView的Adapter中,我们常常会使用ViewHolder, 在该类下需要绑定相关View

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

ButterKnife.bind的调用可以被放在任何你想调用findViewById的地方。

提供的其他绑定API:

  • 使用Activity作为跟布局在任意对象中进行绑定。如果你使用了类似MVC的编程模式,你可以对controller使用它的Activity用ButterKnife.bind(this, activity)进行绑定。
  • 使用ButterKnife.bind(this)绑定一个布局的子布局。如果你在布局中使用了标签并且在自定义的控件构造时inflate这个布局,你可以在inflate之后立即调用它。或者,你可以在onFinishInflate()回调中使用它。

2.5 其他特性

1. 绑定View列表

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

2. 对View应用动作

apply函数,该函数一次性在列表中的所有View上执行一个动作:

ButterKnife.apply(nameViews, DISABLE);
ButterKnife.apply(nameViews, ENABLED, false);
           

Action和Setter接口能够让你指定一些简单的动作:

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

3. 对View应用属性

Android中的Property属性也可以使用apply方法进行设置:

2.6 监听器绑定

使用本框架,监听器能够自动的绑定到特定的执行方法上:

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

而监听器方法的参数都时可选的:

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

指定一个特定的类型,Butter Knife也能识别:

@OnClick(R.id.submit)
public void sayHi(Button button) {
    button.setText("Hello!");
}
           

可以指定多个View ID到一个方法上,这样,这个方法就成为了这些View的共同事件处理。

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

自定义View时,绑定事件监听不需要指定ID

public class FancyButton extends Button {
    @OnClick
    public void onClick() {
        // TODO do something!
    }
}
           

2.7 重置绑定

Fragment的生命周期与Activity不同。在Fragment中,如果你在onCreateView中使用绑定,那么你需要在onDestroyView中设置所有view为null。为此,ButterKnife返回一个Unbinder实例以便于你进行这项处理。在合适的生命周期回调中调用unbind函数就可完成重置。

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

2.8 可选绑定

可选绑定:

在默认情况下, @bind和监听器的绑定都是必须的,如果目标view没有找到的话,Butter Knife将会抛出个异常。

如果你并不想使用这样的默认行为而是想创建一个可选的绑定,那么你只需要在变量上使用@Nullable注解或在函数上使用@Option注解。

注意:任何名为@Nullable的注解都可以使用在变量上。但还时强烈建议使用Android注解库中的@Nullable。

@Nullable @BindView(R.id.might_not_be_there) TextView mightNotBeThere;

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

2.9 对包含多个监听方法的绑定——ListView OnItemSelectedListener

@OnItemSelected(R.id.list_view)
void onItemSelected(int position) {
    // TODO ...
}

@OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED)
void onNothingSelected() {
    // TODO ...
}
           

2.10 Butter Knife简单findById方法

Butter Knife提供了一个findViewById的简化代码:findById,用这个方法可以在View、Activity和Dialog中找到想要View,而且,该方法使用的泛型来对返回值进行转换,也就是说,你可以省去findViewById前面的强制转换了。

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

3. Android Studio的插件——Android ButterKnife Zelezny

Android Butter Knife使用详解

配合ButterKnife实现注解,从此不用写findViewById,想着就爽啊。在Activity,Fragment,Adapter中选中布局xml的资源id自动生成butterknife注解。

使用方法:Ctrl+Shift+B选择图上所示选项.

继续阅读