简体   繁体   中英

Keep Bitmap in ImageView when Change Fragment with ViewModel

I have two Fragment that I bundle bitmap between them.

in FragmentA , I select Image From Gallery and Camera and set it in ImageView as Bitmap

and I will bundle that bitmap when I navigate to HomeFragmrnt and get it and Set it in ImageView in HomeFrag as Bitmap again!

PROBLEM: When I leave the FragmentA to FragmentB and back again to SettingFrag I lose the ImageView ! and when I leave the FragmentB I lose the image again!

I know it is for Fragment Lifecycle and I try to use savedInstance but do not work!

I have ViewModel class for FragmentA and FragmentB ? how can I handle my problem with it ?!

if you want any code I will post it!

Thank you

You can share any data between fragments using ViewModel.

In your case, create a variable in ViewModel in the following way:

var mBitmap: Bitmap? = null

and then when you get the bitmap, assign that bitmap to above variable from your fragment

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

mViewModel.mBitmap = bitmap 

after this wherever you want to use this bitmap just call this:

mViewModel.mBitmap

for example, something like this:

imageView.setImageBitmap(mViewModel.mBitmap)

Hope this helps, let me know if you need anything

Update:

Like Ajeeli mentioned pass the activity instance while initializing the ViewModel

ViewModelProvider(activity, viewModelFactory).get(SettingViewModel::class.java)

Your issue could be that you are scoping your ViewModel to the fragment only when it should be scoped to the activity lifecycle.

Change this:

ViewModelProvider(this, viewModelFactory)

To:

ViewModelProvider(requireActivity(), viewModelFactory)

I solved the problem tnx @parag Pawar

I used SharedPrefrences ! Just it!

I put the Image File in SharedPrefrences and get it in another Fragment! The Image Saved and everything was good!

   lateinit var preferences: SharedPreferences
    lateinit var editor: SharedPreferences.Editor


    companion object {
 const val PREF: String = "PREF_KEY"
        const val IMG_KEY: String = "IMG_PATH"
}



    preferences = activity!!.getSharedPreferences(PREF, Context.MODE_PRIVATE)
    editor = preferences.edit()



 editor.putString(IMG_KEY, data.data.toString())
                    editor.apply()

//here u get the value

    val sharedPreference: SharedPreferences = activity!!.getSharedPreferences(
        PREF, Context.MODE_PRIVATE
    )
    if (sharedPreference.contains(IMG_KEY)) {
        imgPath = sharedPreference.getString(
            IMG_KEY,
            null
        ).toString()
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM