为了摆脱我们的findviewbyid这个没有什么意义的单纯的体力劳动。我们开始使用这个懒人库吧。
)首先Add this to you project-level build.gradle
:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
Add this to your module-level build.gradle
:
apply plugin: 'android-apt'
android {
...
}
dependencies {
compile 'com.jakewharton:butterknife:8.0.1'
apt 'com.jakewharton:butterknife-compiler:8.0.1'
}
Make sure the line apply plugin ...
is placed somewhere at the top of the file
然后rebuild一下工程。
然后,需要各种绑定,下面依次介绍,由于暂时只碰见这三种,所以就写了这三种。应该是比较常用的。
1)如果是activity中,只需要在setcontentview()后面写这么一句。就可以了
然后就可以这个样子
就是在我们声明成员变量的时候,就和我们平常的声明是一样的
@bind(R.id.textview)
TextView tv_show;
之后的使用就可以直接用
tv_show.setText("hello.it is easy");
或者
btn_send.setOnclickListener(new OnclickListener(){
public void run(){
//to do what you want to do
}
})
2)如果说在fragment中进行使用的时候
在我们的在获得子view的布局之后。
Context mContext=getActivity();
ButterKnife.bind(mContext,view);
就像这样子
3)如果是在viewholder中使用的时候
我们在构造函数之后通过
ButterKnife.bind(mcontext,view);
或者是
ButterKnife.bind(this,view);
就像下面这样子
完美。
但是人,还可以更懒,这个时候需要一个插件叫做android-butterknife-zelezny
这是git上这个插件的的地址
How to install
- in Android Studio: go to
Preferences → Plugins → Browse repositories
and search forButterKnife Zelezny
在setting界面(ctrl+alt+s)打开就可以 file——》setting-》plugins-》搜索,然后安装-》然后重启android studio
How to use it
- Make sure you have latest Butterknife lib on your classpath
- Right click on usage of desired layout reference (e.g. R.layout.main in your Activity or Fragment), then
Generate
andGenerate ButterKnife Injections
- Pick injections you want, you also have an option to create ViewHolder for adapters.
- Click
Confirm
and enjoy injections in your code with no work!
注意,确保自己已经有了之前的ButterKnife,然后安装好这个插件之后。光标放到我们的xml布局文件上,然后右键,选择generate,然后选择generate butterKnife injections 然后选择就可以了,需要对哪些控件进行绑定,需要更改名字。然后确定就可以。
完美~
然后rebuild一下工程。