Android ButterKnife 注解与依赖注入框架 – 编译时注解(一)
Android ButterKnife 注解与依赖注入框架 – 编译时注解(一)
原文:https://ke.qq.com/course/130901
编译时技术:
动态生成数据,无需反射,完全没有性能消耗
因为导入最新 ButterKnife 报错,原因查看这里
本文对应的版本:8.2.1
自动生成代码插件 Android ButterKnife Zelezny —— Ctrl + Alt + B
// 项目APPgradle导入下面代码最新版需要升级 Gradle 到最新,因为ButterKnife与Androidx冲突
implementation 'com.jakewharton:butterknife:8.2.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.2.1'
// 使用
public class MainActivity extends AppCompatActivity {
@BindView(R.id.btn)
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick(R.id.btn)
public void onViewClicked() {
Toast.makeText(this, btn.toString(), Toast.LENGTH_SHORT).show();
}
}
// activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
查看 ButterKnife 8.2.1 源码
这里是一个接口,每一个接口都要有一个实现类去完成它的功能。但是这个接口的实现类并不在源码中,当项目编译完成后才会生成对应的实现类。
ButterKnife 会生成下面两个文件(用文件流生成文件IO流)
这些相关的源码只有在编译后,才会自动生成。所以以后要研究这些类似的框架时,需要自己使用后 (编译)才能看到这些框架的源码。