您的位置:首页 > Web前端

Butterknife使用文档

2017-03-14 14:31 239 查看
介绍

butterknife是一个非常强大的视图绑定库,大大简化代码,并且不会因为反射而影响APP性能,所以推荐使用

英文链接

使用@BindView

这个注解和一个view的ID来自动的匹配到布局中的view。

public 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.example_activity);
ButterKnife.bind(this);
// TODO Use fields...
}
}


代替耗时的反射,通过产生代码来实现view的查找,可以叫做委托绑定并产生可见且可调式的代码。

上面的例子产生的代码大致如下:

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


资源绑定

用@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
// …
}


没有活动的绑定

你也可以绑定随意的对象,但是必须提供你的view根节点

public class FancyFragment extends Fragment {
@BindView(R.id.button1)
Button button1;
@BindView(R.id.button2)
Button button2;
@Override
4000

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


另一个用法是在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);
}
}
}


你可以在提供的示例中看到它的实现

其他的绑定APIs

如果活动是视图的根节点,如果你使用MVC的设计模式,你可以在控制器中使用ButterKnife.bind(this, activity).来完成绑定

用ButterKnife.bind(this)来绑定子视图,如果你在布局中使用了merge标签在一个自定义的视图里你可以立刻使用,或者从xml中填充自定义视图,可以在onFinishInflate()回调中使用。

视图列表

你可以把视图放在一个数组或者列表里

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


使用这几种方法允许您立即在列表中的所有视图上执行

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

动作和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);
}
};


一个安卓的属性方法也可以一同使用。

ButterKnife.apply(nameViews, View.ALPHA, 0.0f);


监听器绑定

监听器也可以简单自然的绑定在方法中

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


也可以制定一个具体的类型

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


常规的事件绑定多个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();
}
}


常规的视图可以被绑定到他们自己的监听器不需要具体的ID

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


绑定重置

Fragment有和activity不一样的生命周期,当绑定一个fragment的在onCreate,在销毁时(onDestroyView)

设置视图们变为空,Butter Knife返回一个Unbinderinstance当你调用绑定方法,并在合适的地方调用解绑方法。

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


可选择的绑定

默认的,普通绑定和监听器绑定都是需要的,如果找不到view可以能会抛异常。

要抑制此行为并创建可选绑定,添加一个@Nullable注释在字段前,或者 @Optional在方法前。

注意:任何注释@Nullable可以被用在字段前,Android’s “support-annotations” library也是鼓励这么使用。

@Nullable @BindView(R.id.might_not_be_there)
TextView mightNotBeThere;
@Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {
// TODO …

}


多元监听

方法前的注释可以有多元化的监听回调,每个注释可以默认回调它的绑定,具体制定一个参数(int position)

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


额外的优势

也包含findById方法使代码简单,来找到视图活动弹窗的views。它使用泛型来判断类型并自动转换。

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


配置

1.在Project级别的 build.gradle 中包含“android-apt”:

buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}


2.然后在module级别的build.gradle中,添加依赖:

apply plugin: 'android-apt'

dependencies {
compile ‘com.jakewharton:butterknife:8.4.0’
apt ‘com.jakewharton:butterknife-compiler:8.4.0’
}


代码混淆

-keep class butterknife.** { *; }
-dontwarn butterknife.internal.**
-keep class **$$ViewBinder { *; }
-keepclasseswithmembernames class * {
@butterknife.* <fields>;
}
-keepclasseswithmembernames class * {
@butterknife.* <methods>;
}


使用注意

1.Activity ButterKnife.bind(this);必须在setContentView();之后,且父类bind绑定后,子类不需要再bind。

2.Fragment ButterKnife.bind(this, mRootView);记得解绑

3.属性布局不能用private or static 修饰,否则会报错 ;

@BindView(R.id.button1)
private  Button button1;


4.setContentView()不能通过注解实现

Android studio 中ButterKnife插件 Zelezny 应用

在AndroidStudio->File->Settings->Plugins->搜索Zelezny下载添加就行 ,可以快速生成对应组件的实例对象,不用手动写。

使用时,在要导入注解的Activity 或 Fragment 或 ViewHolder的layout资源代码上,右键——>Generate——Generate ButterKnife Injections,然后就出现选择框。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  butterknif