AndroidStudio使用Butterknife

好记性不如烂笔头,这句话是真的。

在Android中我们经常要做很多的无用功,比如诸多的findViewById(),后来ButterKnife出来了,一时间大家都说好,我也在项目中用到了,在这里记录一下。

1.下载插件

我这里用的是AndroidStudio,可以在File -> Settings -> Plugins 里面搜索Butterknife下载安装,装完重启。

2.在项目根目录下的build.gradle中配置

classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8’

示例

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

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
3.在module的build.gradle中配置

首先在最上面使用插件

apply plugin: ‘android-apt’

示例

apply plugin: 'com.android.application'
apply plugin: 'android-apt'

然后在dependencies中添加引用

compile 'com.jakewharton:butterknife:8.6.0'

apt 'com.jakewharton:butterknife-compiler:8.6.0'

示例

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'

    //butterknife
    compile 'com.jakewharton:butterknife:8.6.0'
    apt 'com.jakewharton:butterknife-compiler:8.6.0'
}

至此,ButterKnife的准备工作告一段落了,下面开始使用

在Activity中,将光标放在资源文件的名称上,然后鼠标右键,选择Generate(快捷键:Alt + Insert)
,在出来的弹框中选择 Generate ButterKnife Injections选项,在出来的弹框中选择你要做的操作
就可以了

有时候会在Adapter中使用,例如RecyclerView的Adapter,其实也是很简单的

示例

class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.btn_item)
        Button btn_item;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

在AndroidStudio更新到3.0之后发现上面的配置不能用了,这里记录下解决方法

  • 首先把项目下的build.gradle中的classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8’删掉

  • 把module下面的build.gradle最上面引入的插件删掉,不管是下面这两个中的哪一个,都删掉

    • apply plugin: ‘com.neenbedankt.android-apt’
    • apply plugin: ‘android-apt’
  • 在module下的build.gradle中的依赖修改为

    // butterknife   组件注入
    implementation 'com.jakewharton:butterknife:8.6.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
    

经过这三步就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值