我是Kotlin和ViewModel使用的新手。 我正在尝试创建一个简单的ViewModel,它具有字符串列表。 想法是在此ViewModel中更新图片路径列表(字符串)。
我的问题是我的ViewModel没有更新。它只会添加1个条目。
class PicturesViewModel : ViewModel() {
var pictureListLive: MutableLiveData<MutableList<String>> = MutableLiveData()
var list = ArrayList<String>()
fun addPictureToList(picture: String) {
list.add(picture)
pictureListLive.value = list
}
}
在我的活动中,我初始化viewModel并像这样观察:
private fun configureViewModel(){
this.picturesViewModel = ViewModelProviders.of(this).get(PicturesViewModel::class.java!!)
this.picturesViewModel.pictureListLive.observe(this, Observer{
if (it != null) {
Log.i("Pictures",it.size.toString())
}
})
}
然后我在ViewModel中添加一个字符串:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_IMAGE_CAPTURE) {
picturesViewModel.addPictureToList(currentPhotoPath)
val intentPreview = Intent(this,PreviewActivity::class.java)
intentPreview.putExtra("Picture",currentPhotoPath)
startActivity(intentPreview)}
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CHOOSE_PHOTO){
this.pictureSelectedPath = data?.data.toString()
Log.i("Photo",pictureSelectedPath)
}
}
ActivityOnResult来自相机拍照后的结果。我想更新ViewModel的字符串列表,以在拍摄完几张照片后添加照片相机路径。
今天当我像这样使用它时,ViewModel列表的大小保持为1。我认为其中只有最后一个。
感谢您的帮助。
答案 0 :(得分:1)
这是初始化和使用简单ViewModel的用例
//in your pictures fragment
private lateinit var picturesViewModel: PicturesViewModel
比您的onCreate
picturesViewModel= ViewModelProviders.of(this).get(PicturesViewModel::class.java)
初始化视图模型后,您可能会在初始化以下的过程中观察在那里发生的数据更改:
picturesViewModel.pictureListLive.observe(this, Observer {
//list changes are handled here
})
如果我要重写ViewModelClass,它将像这样:
class PictureViewModel : ViewModel() {
private var pictureListLive: MutableLiveData<MutableList<String>> = MutableLiveData()
fun setPictureList(picture: String) {
val list = ArrayList<String>()
list.add(picture)
pictureListLive.value = list
}
}
不需要返回列表,因为MutableLiveData以发布-订阅逻辑(也称为Observable Pattern)工作。
注意
我需要有关该setPictureList
方法的更多信息,因为那样的话,它就没有太多意义了。或者,也许您想在其他地方或idk称呼它。
答案 1 :(得分:0)
2021 年 4 月 10 日在 Android Studio 4.1.3 Kotlin 1.4.32 compileSdkVersion 30.0.3 可能的解决方案:
dependencies {
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.1"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
implementation "androidx.fragment:fragment-ktx:1.3.2"
}
AppCompatActivity 中的代码:创建 ViewModel:
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleOwner
class MainActivity : AppCompatActivity() {
private val picturesViewModel: PicturesViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
picturesViewModel.pictureListLive.observe(this, {
it?.let { Log.i("Pictures", "size = ${it.size} ${if (it.size>0) it[it.size-1]
else "empty"}") }
})
}
调用应用相机并返回结果
private var resultLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
// There are no request codes
val data: Intent? = result.data
val path = result?.data?.getStringExtra(PATH) ?:"sssss"
picturesViewModel.addPictureToList(path)
}
}
fun onClick(view: View) {
val questionIntent = Intent(this, Camera::class.java)
// new call for startActivityForResult:
resultLauncher.launch(questionIntent) }
}
PicturesViewModel.kt:
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class PicturesViewModel : ViewModel() {
var pictureListLive: MutableLiveData<MutableList<String>> =
MutableLiveData(mutableListOf())
fun addPictureToList(picture: String) {
pictureListLive.value?.add(picture)
// so that the observer can see that the list has changed
pictureListLive.value = pictureListLive.value
}
}
结果:
2021-04-10 com.example.kotlinviewmodellistofstring I/Pictures: size = 0 empty
2021-04-10 com.example.kotlinviewmodellistofstring I/Pictures: size = 1 123Path
2021-04-10 com.example.kotlinviewmodellistofstring I/Pictures: size = 2 234Path
2021-04-10 com.example.kotlinviewmodellistofstring I/Pictures: size = 3 Path345
2021-04-10 com.example.kotlinviewmodellistofstring I/Pictures: size = 4 Pa456th
2021-04-10 com.example.kotlinviewmodellistofstring I/Pictures: size = 5 Pa567th
2021-04-10 com.example.kotlinviewmodellistofstring I/Pictures: size = 6 Path678
2021-04-10 com.example.kotlinviewmodellistofstring I/Pictures: size = 7 cam123456