use*_*730 26 android transformation kotlin
我试图按照 android 文档在我的项目中实现 Transformations 但我遇到了这个问题Unresolved reference: Transformations。我不知道为什么我的项目看不到 Transformations 类。
我正在使用 Kotlin 版本 1.5.21',这是我的代码
class MyViewModel(private val repository: PostalCodeRepository) : ViewModel() {
private val addressInput = MutableLiveData<String>()
val postalCode: LiveData<String> = Transformations.switchMap(addressInput) {
address -> repository.getPostCode(address) }
private fun setInput(address: String) {
addressInput.value = address
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢任何指导。
Mor*_*ori 11
如果有一个这样的PageViewModel类
class PageViewModel : ViewModel() {
private val _index = MutableLiveData<Int>()
val text: LiveData<String> = Transformations.map(_index) {
"$it"
}
fun setIndex(index: Int) {
_index.value = index
}
}
Run Code Online (Sandbox Code Playgroud)
新版本可以是这样的:
class PageViewModel : ViewModel() {
private val _index = MutableLiveData<Int>()
val text: LiveData<String> = _index.map { "$it" }
fun setIndex(index: Int) {
_index.value = index
}
}
Run Code Online (Sandbox Code Playgroud)
确保导入
import androidx.lifecycle.Transformations
Run Code Online (Sandbox Code Playgroud)
如果导入出现Unresolved reference错误,请将以下依赖项添加到您的build.gradle文件中
dependencies {
...
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.4.1"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9744 次 |
| 最近记录: |