[使用ViewModel更改片段时保留ImageView中的位图

问题描述 投票:0回答:1

我有两个片段,它们之间捆绑了位图。

SettingFragment中,我从图库相机中选择图像,然后在ImageView中将其设置为Bitmap

并且当我导航到HomeFragmrnt并获得它并将它在HomeFrag的ImageView中再次设置为bitmap时,我将把它捆绑在一起Bitmap

问题:当我离开SettingFragmentHomeFragment并再次回到SettingFrag时,我失去了ImageView!当我离开HomeFragment时,我又失去了图像!

我知道它是针对Fragment Lifecycle的,我尝试使用savedInstance,但不起作用!

我具有SettingFragmentHomeFragmentViewModel类!我该如何解决我的问题?

如果您需要任何代码,我将其发布!

谢谢


UPDATE:

SettingViewModel:

class SettingViewModel @Inject constructor(
    val useCase: DeleteCacheUseCase,
    private val personalUseCase: GetPosPersonalInfoUseCase
) :
    CompletableViewModel<String>(useCase) {



private var _userName: String? = null
val userName get() = _userName

fun getUserInfo() {
    _userName = personalUseCase.getClientUsername()
}

private var _brokerName: String? = null
val brokerName get() = _brokerName

fun getBrokerName() {
    _brokerName = personalUseCase.getBrokerName()
}

SettingFragment:

我在这里拍照或从画廊中挑选:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        if (resultCode == RESULT_OK) {
            when (requestCode) {

                REQUEST_TAKE_PHOTO -> {
                    try {
                        mPhotoFile = mCompressor!!.compressToFile(mPhotoFile!!)
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }

                    bitmap = BitmapFactory.decodeFile(mPhotoFile!!.absolutePath)

                    setBitmapInImage()
                    dismissSheet()


                }

                REQUEST_GALLERY_PHOTO -> {


                    if (data != null) {

                        try {
                            bitmap = MediaStore.Images.Media.getBitmap(
                                context!!.contentResolver,
                                data.data
                            )
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                    }



                    setBitmapInImage()
                    dismissSheet()
                }
            }
        }


    }

这里我在SettingViewModel中初始化SettingFragment

@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val viewModel: SettingViewModel by lazy {
    ViewModelProvider(this, viewModelFactory).get(SettingViewModel::class.java)
}

这里我将位图作为捆绑导航到HomeFragment:

覆盖有趣的navigationToHome(){super.navigateToHome()findNavController()。navigate(SettingFragmentDirections.actionSettingFragmentToHomeFragment(位图))

}

这里我在HomeFragment中得到了捆绑包:

   val bitmapimage =
            arguments?.getParcelable<Bitmap>("profileImage")


        Glide.with(activity!!).load(bitmapimage).apply(
            RequestOptions().centerCrop().circleCrop()
                .placeholder(R.drawable.ic_profile)
        ).into(user_profile_img)

android fragment viewmodel lifecycle
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.