ButterKnife懒人库的使用 摆脱findviewbyid苦力

为了摆脱我们的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 for ButterKnife Zelezny
   在setting界面(ctrl+alt+s)打开就可以  file——》setting-》plugins-》搜索,然后安装-》然后重启android studio

How to use it

  1. Make sure you have latest Butterknife lib on your classpath
  2. Right click on usage of desired layout reference (e.g. R.layout.main in your Activity or Fragment), then Generate andGenerate ButterKnife Injections
  3. Pick injections you want, you also have an option to create ViewHolder for adapters.
  4. Click Confirm and enjoy injections in your code with no work!
注意,确保自己已经有了之前的ButterKnife,然后安装好这个插件之后。光标放到我们的xml布局文件上,然后右键,选择generate,然后选择generate butterKnife injections 然后选择就可以了,需要对哪些控件进行绑定,需要更改名字。然后确定就可以。

完美~





然后rebuild一下工程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值