第 18 章:Kotlin 在 Android 开发中的应用
18.1 Android 项目中的 Kotlin 配置
1. 创建支持 Kotlin 的 Android 项目
在 Android Studio 中创建新项目时,默认会启用 Kotlin 支持。以下是手动配置步骤(适用于旧项目或自定义配置):
在
build.gradle (Project)中添加 Kotlin 插件依赖buildscript { ext.kotlin_version = '1.8.20' // 使用最新稳定版本 dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } }在
build.gradle (Module)中应用 Kotlin 插件plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' }添加 Kotlin 标准库依赖
dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" }
2. 配置 Kotlin 扩展功能
Android Extensions(已废弃,推荐使用 View Binding)
- 旧版配置(仅作参考):
android { androidExtensions { experimental = true } }
View Binding 替代方案
在
build.gradle (Module)中启用 View Binding:android { viewBinding { enabled = true } }在代码中使用:
private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.textView.text = "Hello Kotlin!" }
3. Kotlin 与 Java 互操作配置
处理空安全性警告:
在 Java 代码中添加@Nullable或@NonNull注解,或在 Kotlin 中使用平台类型(String!)。SAM 转换支持:
对于 Java 接口(如Runnable),Kotlin 自动支持 SAM 转换:button.setOnClickListener { /* Lambda 表达式 */ }
4. 启用 Kotlin 协程(Coroutines)
添加协程依赖:
dependencies { implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4' }在代码中使用协程:
lifecycleScope.launch { val result = withContext(Dispatchers.IO) { fetchData() } binding.textView.text = result }
5. 其他实用配置
启用 Parcelize 序列化
添加插件依赖:
plugins { id 'kotlin-parcelize' }使用
@Parcelize注解:@Parcelize data class User(val name: String, val age: Int) : Parcelable
启用 KAPT(Kotlin 注解处理器)
用于 Room、Dagger 等库:
plugins {
id 'kotlin-kapt'
}
dependencies {
kapt "androidx.room:room-compiler:2.5.0"
}
6. 常见问题与解决
问题 1:Kotlin 版本冲突
解决:确保所有模块的kotlin-stdlib版本一致。问题 2:Java 8 兼容性
解决:在build.gradle中配置:android { compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } }
通过以上配置,你的 Android 项目将完全支持 Kotlin 开发,并能够利用其现代语言特性提升开发效率!
