项目github地址:https://github.com/JakeWharton/butterknife
ButterKnife是一个专注于Android系统的View注入框架,可以减少大量的findViewById以及setOnClickListener代码,使代码更加简洁。
添加依赖:
在项目的project 的build.gredle 文件中的dependencies标签下添加。
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'//添加此句
}
}
在module的build.gredle 文件中添加
apply plugin: 'com.android.application'
apply plugin: 'android-apt'//添加此句
在module的build.gredle 文件中的dependencies标签中添加
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:support-v4:24.2.0'
compile 'com.google.code.gson:gson:2.8.0'
//butterknife,添加下面这两句
compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
}
安装插件
使用
有两个方法,一个在activity中的绑定,一个是在别的布局中绑定,这里我要绑定到一个自定义布局中,使用第二种方法,有两个参数的方法;
public class MainTitleBar extends LinearLayout {
public MainTitleBar(Context context) {
super(context);
}
public MainTitleBar(Context context, AttributeSet attrs) {
super(context, attrs);
mTitlebarView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.main_tilte_bar, this);
//第一个参数为绑定目标,第二个参数为要绑定的view
ButterKnife.bind(this, mTitlebarView);
}
}
鼠标箭头移动到R.layout.main_tilte_bar上,点击右键
点击Generate
点击Generate ButterKnife Injection
更具需要选择
生成效果