Android视图组件注入工具ButterKnife使用说明

From the Butterknife github page:

Add this to you project-level build.gradle:

 repositories {
 mavenCentral()
 }
 dependencies {
 classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
 }
}

(update for 8.8.1:
classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'
Instead of the old)

Add this to your module-level build.gradle:


android {
 ...
}
dependencies {
 compile 'com.jakewharton:butterknife:8.0.1'
 apt 'com.jakewharton:butterknife-compiler:8.0.1'
}

注意app的build.gradle中的顶部apply plugin(处于最外层)

(update for 8.8.1 : try annotationProcessor instead of apt)

Added support for the annotationProcessor configuration provided by Android Gradle Plugin 2.2.0 or later.

升级到Android Studio3.0后,且Android Gradle Plugin 升级到2.2.0后,提供了annotationProcessor及Kotlin的kapt。需替换
apt 'com.jakewharton:butterknife-compiler:8.0.1'
为:
annotationProcessor 'com.jakewharton:butterknife-compiler:8.0.1'
同时删掉apply plugin

使用

View 及 Fragment 中使用:

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.*fragment_lcs*, container, false); 
    ButterKnife.bind(this, rootView);
    return rootView;
 }

Or in activity使用:

@Override protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); setContentView(R.layout.*activity_demo*); 
    ButterKnife.bind(this);
}

成员变量中声明并添加注解,例如:

    @BindView(R.id.main_title)
    TextView mainTitle;
    @BindView(R.id.sub_title)
    TextView subTitle;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,138评论 25 709
  • 博客原文链接 Android百大框架排行榜(转) 说明: 无聊写一篇笔记式文章. 精力有限,很多错误之处,受时间与...
    码农朱同学阅读 2,771评论 0 27
  • 一.榜单介绍 排行榜包括四大类: 单一框架:仅提供路由、网络层、UI层、通信层或其他单一功能的框架 混合开发框架:...
    伟子男阅读 5,276评论 0 161
  • mqtt协议学习与使用 一.先简单介绍一下mqtt协议 mqtt协议是基于Tcp/ip 的一种通信协议,是建立在可...
    lennasu阅读 847评论 0 0
  • 2015.12.06 外面的世界一直在变,又好像一直都没变。树不是因为想落叶于是就落叶,天不是因为想起雾所以就起雾...
    XinSuting阅读 573评论 0 0