ButterKnife框架使用详解

一、ButterKnife的简介:

在开发过程中,我们总是会写大量的findViewById和点击事件,像初始view、设置view监听这样简单而重复的操作让人觉得特别麻烦,当然不会偷懒的程序员不是好程序员,自然也出现了相应的解决方案--依赖注入

而ButterKnife则是依赖注入中相对简单易懂的很不错的开源框架,(其实ButterKnife也不算严格意义上的依赖注入,后面文章中会做分析)。但ButterKnife作为JakeWharton大神写的注解框架被广泛应用于android开发中,自然也有它的过人之处。


二、使用方法

导入ButterKnife至项目中

1.在工程的build.gradle中导入butterknife插件 (看清楚了,是工程得bulid.gradle,不是app下得)
这里写图片描述


buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        //加入下面这段代码
        classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

2.在项目的build.gradle中添加butterknife的插件,即是app中的builde.gradle (app下得bulid.gradle)
这里写图片描述

apply plugin: 'com.android.application'
//加入下面这段代码
apply plugin: 'com.jakewharton.butterknife'

3.在项目的build.gradle中添加依赖,然后同步项目,即可下载butterknife库至项目中

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile 'com.android.support:appcompat-v7:25.2.0'

    //加入下面这两行代码
    compile 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'

}

简单使用butterknife初始化控件

1.创建一个android工程,布局如下 
这里写图片描述

2.在activity中的oncreate()方法里初始化butterknife框架 
注意初始化要放在setView()之后

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_butter_knife_test);
        ButterKnife.bind(this);
    }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3.查找TextView与Button

public class ButterKnifeTestActivity extends AppCompatActivity {
    //绑定控件,省去了写findviewbyid的重复性操作
    @BindView(R.id.tv_test1)
    private TextView tvTest;
    @BindView(R.id.btn_test1)
    private Button btnTest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_butter_knife_test);
        ButterKnife.bind(this);
    }
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

4.测试控件是否被正确初始化

  tvTest.setText("文本控件已被初始化");
  btnTest.setText("按钮被初始化");注意:运行此项目得时候 会报错:这里写图片描述

所以ButterKnife使用中有哪些注意的:

  1. Activity ButterKnife.bind(this);必须在setContentView();之后,且父类bind绑定后,子类不需要再bind
  2. Fragment ButterKnife.bind(this, mRootView);
  3. 属性布局不能用private or static 修饰,否则会报错
  4. setContentView()不能通过注解实现。
  5. ButterKnife已经更新到版本7.0.1了,以前的版本中叫做@InjectView了,而现在改用叫@Bind,更加贴合语义。
  6. 在Fragment生命周期中,onDestoryView也需要Butterknife.unbind(this)
  7. ButterKnife不能再你的library module中使用哦!!这是因为你的library中的R字段的id值不是final类型的,但是你自己的应用module中确是final类型的。针对这个问题,有人在Jack的github上issue过这个问题,他本人也做了回答,点击这里




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值