kik*_*ike 15 android kotlin android-livedata android-architecture-components
我正在尝试使用Android文档中描述的LiveData实现DB Observer .
只要我在Kotlin编程,我就会调整函数(最初用Java编写).
在尝试保存数据时,我发现了这个问题.
Cannot assign to ‘value’: the setter is protected/*protected and package*/ for synthetic extension in ‘<library Grade: android.arch.livecycle:livedata-core-1.1.1>’
Run Code Online (Sandbox Code Playgroud)
有人有这个问题吗?
这是我的代码:
视图模型:
class ProfileViewModel: ViewModel() {
object FirstName: MutableLiveData<String>()
fun getCurrentName(): LiveData<String> {
return FirstName
}
}
Run Code Online (Sandbox Code Playgroud)
分段
class ProfileFragment{
private lateinit var model: ProfileViewModel
// this is called onViewCreated. inputFirstName is an Edittext.
override fun setUp() {
model = ViewModelProviders.of(this).get(ProfileViewModel::class.java)
val nameObserver = Observer<String> { firstName ->
inputFirstName.text = SpannableStringBuilder(firstName)
}
model.getCurrentName().observe(this, nameObserver)
}
fun saveProfileData() {
val firstName = inputFirstName.text.toString()
model.getCurrentName().value = firstName
}
}
Run Code Online (Sandbox Code Playgroud)
小智 22
正如@spkink建议:
更换
fun getCurrentName(): LiveData<String>
Run Code Online (Sandbox Code Playgroud)
同
fun getCurrentName(): MutableLiveData<String>
Run Code Online (Sandbox Code Playgroud)
这个错误是因为造成setValue(T value)是protected在LiveData(所以你不能把它),而这是public在MutableLiveData.
| 归档时间: |
|
| 查看次数: |
4402 次 |
| 最近记录: |