写在前面:
在github上butterknife的star有11000+
为啥有这么多人用这个插件
两点:
1、自动化
2、有人更新和维护
GRADLE
根目录的build.gradle
也就是project级
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
module级别
apply plugin: 'android-apt'
android {
...
}
dependencies {
compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
}
基本的注入我想大部分人都知道
ButterKnife.bind(this)
这里可以是View,Activity等等
还支持Android annotations的几个注解
@Optional 可选
@Nullable 可能为空
在8.4.0中最大的改动可能就是使用R2代替R文件
我觉得这个可能是为了自动生成R文件经常出现问题的解决方案
应该是和Android Studio中的instant run有冲突
变量的注入
@BindView
TextView textView;
@BindString(R.string.title)
String title;
@BindDrawable(R.drawable.graphic)
Drawable graphic;
@BindColor(R.color.red)
int red;
@BindDimen(R.dimen.spacer) Float spacer; // int (for pixel size) or float (for exact value) field
上面来自于官网
可以修改View的属性
An Android Property can also be used with the apply method.
ButterKnife.apply(nameViews, View.ALPHA, 0.0f);
onclick事件
//单View的写法
@OnClick(R.id.submit)
public void submit(View view) {
// TODO submit data to server...
}
//也可以不写View参数
@OnClick(R.id.submit)
public void submit() {
// TODO submit data to server...
}
//也可以将参数进行强转
@OnClick(R.id.submit)
public void sayHi(Button button) {
button.setText("Hello!");
}
//也可以是一个数组,这里批量注入
@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!
}
}
一些特殊的点击事件
@OnItemSelected(R.id.list_view)
void onItemSelected(int position) {
// TODO ...
}
@OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED)
void onNothingSelected() {
// TODO ...
}
官网还有一个bouns,看起来是省去了强转,可以用在dialog等地方
BONUS
Also included are findById methods which simplify code that still has to find views on a View, 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.
android studio中有插件哦
搜索Butterknife
默认快捷键是alt+insert 然后选Butterknife那个
当然有一个ctrl+shift+B的快捷键,应该是和其他的有冲突了
暂时先这样