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

2018-02-24  本文已影响0人  MatsuiRakuyo

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;
上一篇下一篇

猜你喜欢

热点阅读