반응형
1. 프로젝트 build.gradle
id 'com.google.dagger.hilt.android' version '2.44' apply false
2. app 모듈 build.gradle
plugins {
...
id 'kotlin-kapt'
id 'com.google.dagger.hilt.android'
}
android {
...
}
dependencies {
...
implementation "com.google.dagger:hilt-android:2.44"
kapt "com.google.dagger:hilt-compiler:2.44"
}
kapt {
correctErrorTypes true
}
3. Application 생성 및 Annotation 추가
@HiltAndroidApp
class RootApplication: Application()
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:name=".RootApplication"
...>
...
</application>
</manifest>
4. Adapter Interface 생성
interface ColorAdapter { fun randomColor(): Int }
5. Adapter Impl class 생성
class ColorImpl: ColorAdapter {
override fun randomColor(): Int {
val rnd = Random()
return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))
}
}
6. 객체 연결 및 Module 생성
@Module
@InstallIn(SingletonComponent::class)
class ColorModule {
@Provides
@Singleton
fun getColorAdapter(): ColorAdapter = ColorImpl()
}
7. 객체 사용
@AndroidEntryPoint
class MainActivity: BaseActivity<ActivityMainBinding>({ ActivityMainBinding.inflate(it) }) {
@Inject lateinit var colorAdapter: ColorAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.randomColor.setOnClickListener {
val randomColor = colorAdapter.randomColor()
colorUpdate(randomColor)
}
}
private fun colorUpdate(color: Int) {
binding.colorView.setBackgroundColor(color)
binding.colorCode.text = String.format("#%06X", 0xFFFFFF and color)
}
}
## 안드로이드 Hilt 종속성 참고 사이트 ##
https://developer.android.com/training/dependency-injection/hilt-android?hl=ko
반응형
'안드로이드' 카테고리의 다른 글
[Android][Kotlin] buildSrc Version Catalog 사용하기 (0) | 2024.06.28 |
---|---|
[Android][Kotlin] 화면 사이즈 구하기(Size) (0) | 2024.05.16 |
[Android][Kotlin] Activity, Fragment by viewModels() 사용 및 종속성 (0) | 2024.04.23 |
[Android][Kotlin] setOnClickListener 단시간 내 중복 방지 및 동시 터치 방지 (0) | 2024.03.29 |
[Android][Kotlin] 카메라, 갤러리, 내 파일 연결 프로그램 만들기 (0) | 2023.12.15 |