<>前言:
<>一、Android Hilt依赖注入框架的引入步骤如下:
<>1.引入Hilt,在App的Build.gradle目录下添加hilt插件和依赖:
plugins { id 'com.android.application' id 'kotlin-android' id 'kotlin-kapt' id
'dagger.hilt.android.plugin' }
//Dagger - Hilt implementation "com.google.dagger:hilt-android:2.30" kapt
"com.google.dagger:hilt-android-compiler:2.30" implementation
"androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03" kapt
"androidx.hilt:hilt-compiler:1.0.0" // Activity KTX for viewModels()
implementation"androidx.activity:activity-ktx:1.3.1"
<>2.在项目的build.gradle目录下添加hilt的插件依赖:
buildscript { ext.kotlin_version = "1.5.21" repositories { google() jcenter() }
dependencies{ classpath "com.android.tools.build:gradle:4.1.1" classpath
"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath
"com.google.dagger:hilt-android-gradle-plugin:2.28.3-alpha" // NOTE: Do not
place your application dependencies here; they belong // in the individual
module build.gradle files } }
<>3.在项目中使用Java8
compileOptions { sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8'
}
<>二、Hilt的简单使用
<>1.创建App类,继承于Application
@HiltAndroidApp class App :Application(){ }
<>2.在Manifast中注册Application
<application android:name=".app.App" android:allowBackup="true"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true"
android:theme="@style/Theme.AndroidDeviceIdDemo"> <activity
android:name=".MainActivity"> <intent-filter> <action
android:name="android.intent.action.MAIN" /> <category
android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
</application>
<>3.将依赖注入到MainActivity类
注:在 Application 类中设置了 Hilt 且有了应用级组件后,Hilt 可以为带有 @AndroidEntryPoint 注释的其他
Android 类提供依赖项
Hilt 目前支持以下 Android 类:
Application(通过使用 @HiltAndroidApp)
Activity
Fragment
View
Service
BroadcastReceiver
<>4.创建注入类:
@Module @InstallIn(ActivityComponent::class) object MainModule {
@ActivityScoped @Provides @Named("String2") fun provideTestString2(
@ApplicationContext context: Context, @Named("String1") testString1: String ) =
"${context.getString(R.string.string_to_inject)} - $testString1" }
@Module @InstallIn(ApplicationComponent::class) object AppModule { @Singleton
@Provides @Named("String1") fun provideTestString1() = "This is a string we
will inject" }
class TestViewModel @ViewModelInject constructor(@Named("String2") testString2:
String) :ViewModel(){ init { Log.d("ViewModel", "Test String from ViewModel: $
testString2") } }
<>5.把创建好的测试类注入到MainActivity中:
@Inject @Named("String1") lateinit var testString: String private val viewModel
: TestViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle
?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)
Log.d("MainActivity", "Test String from MainActivity: $testString") viewModel }
<>6.运行结果如下:
<>7.完整的demo地址:
hint的简单使用
<>8.参考资料:
hint参考资料