kotlin-dagger2

Kotlin 项目中使用 Dagger2,暂时 @Module @Component 还有 Application需要使用 Java文件,然后 Koltin 调用。否则没有办法生成代码。

文件列表

生成代码

1
2
3
4
5
6
package xyz.hanks.kotlindagger
/**
* Created by hanks on 16/3/20.
*/
class Keyboard(var type: String?)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Created by hanks on 16/3/20.
*/
@Module
public class KeyboardModule {
String keyboardType;
public KeyboardModule(String keyboardType) {
this.keyboardType = keyboardType;
}
@Provides
@Singleton
public Keyboard provideKeyboard() {
return new Keyboard(keyboardType);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package xyz.hanks.kotlindagger;
import javax.inject.Singleton;
import dagger.Component;
/**
* Created by hanks on 16/3/20.
*/
@Singleton
@Component(modules = {KeyboardModule.class})
public interface KeyboardComponent {
void inject(MainActivity activity);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package xyz.hanks.kotlindagger;
import android.app.Application;
/**
* Created by hanks on 16/3/20.
*/
public class MyApp extends Application {
KeyboardComponent mKeyboardComponent;
@Override public void onCreate() {
super.onCreate();
mKeyboardComponent = DaggerKeyboardComponent.builder()
.keyboardModule(new KeyboardModule("茶轴"))
.build();
}
public KeyboardComponent getKeyboardComponent() {
return mKeyboardComponent;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package xyz.hanks.kotlindagger
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import javax.inject.Inject
class MainActivity : AppCompatActivity() {
@Inject @JvmField var mKeyboard: Keyboard ? = null // 注意使用@JvmField
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
(applicationContext as MyApp).keyboardComponent?.inject(this)
Toast.makeText(application, mKeyboard?.type, Toast.LENGTH_LONG).show()
}
}

或者参考 dagger2-kotlin,其中使用 kapt 生成代码。
Better Annotation Processing: Supporting Stubs in kapt

文章来自: https://hanks.pub