dependencies {
...
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.38.1'
}
dependencies {
...
implementation 'com.google.dagger:hilt-android:2.38.1'
kapt 'com.google.dagger:hilt-android-compiler:2.38.1'
}
@HiltAndroidApp
class MyApplication : Application() {
}
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val viewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
@AndroidEntryPoint
class MyFragment : Fragment(R.layout.fragment_my) {
private val viewModel: MainViewModel by activityViewModels()
...
}
在以上示例中,使用@ActivityRetainedScoped注解标注的ViewModel将会在Activity被销毁并重新创建时保留其状态。而使用@ViewModelInject注解标注的ViewModel会在每次创建Fragment时被创建和注入。