Dagger是真正的inject。Butter Knife的确不是严格意义上的注入,之所以会叫View injection,Butter Knife可以直接叫他是findViewById 都没问题。
1. 添加插件依赖, 在根目录下的build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
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
}
}
2.在app下添加依赖
上面的位置
apply plugin: 'com.neenbedankt.android-apt'
下面
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
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:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.google.dagger:dagger:2.2'
compile 'org.glassfish:javax.annotation:10.0-b28'
compile 'com.jakewharton:butterknife:7.0.1'
apt 'com.google.dagger:dagger-compiler:2.2'
}
3.页面布局
上面是TextView. 下面是Button, 点击Button更新UI
4. 各个class的代码
其中mainActiviity中, DaggerAppComponent要在crel+F9之后才会生成, 是dragger2自动生成的.
(1)common/IPresenter
public interface IPresenter {
void loadData();
}
(2)common/IView
public interface IView {
void updateUi(String data);
}
(3)包/AppComponent
@Component(modules = MyModule.class)
public interface AppComponent {
void inject(MainActivity activity);
}
(4)包/MyModule
@Module
public class MyModule {
private IView mainView;
public MyModule(IView mainView){
this.mainView = mainView;
}
@Provides
public MyPresenter provideMyPresenter(){
return new MyPresenter(mainView);
}
}
(5)包/MyPresenter
public class MyPresenter implements IPresenter {
private IView mainView;
@Inject
public MyPresenter(IView view){
mainView = view;
}
@Override
public void loadData() {
mainView.updateUi("Random num is " + Math.random()*1000);
}
}
(6)包/MainActivity
public class MainActivity extends AppCompatActivity implements IView, View.OnClickListener {
@Bind(R.id.result)
TextView tv_result;
@Bind(R.id.btn_update)
Button btn_update;
@Inject
MyPresenter myPresenter; //获取依赖的对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
btn_update.setOnClickListener(this);
DaggerAppComponent.builder()
.myModule(new MyModule(this))
.build()
.inject(this); //注入
}
@Override
public void updateUi(String data) {
tv_result.setText(data);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_update:
myPresenter.loadData();
break;
}
}
}