Send data from fragment to another when we use dependency injection for fragments

543 views Asked by At

Is there a way for sending data from a fragment to another without create new instance from it ?

I inject my fragment but i faced with a problem that i describe it in below :

We inject our fragments like this :

val fragmentModule= module {

    factory { MyFragment() }
}

And this is a function for replace fragment :

fun AppCompatActivity.replaceFragment(fragment: Class<out Fragment>,frameId: Int){

    supportFragmentManager
        .beginTransaction()
        .replace(frameId,fragment,null,null)
        .commit()
}

Then i use it like this :

activity.replaceFragment(MyFragment::class.java,R.id.frameLayoutId)

So my question is how can i set argument to fragment in this way and without create new instance of fragment how can we pass a data ?

    val bundle=Bundle()
    bundle.putString("YourKey","YourData")
    val fragment=MyFragment()
    fragment.arguments=bundle
1

There are 1 answers

1
SpiritCrusher On BEST ANSWER

without create new instance? NO . Dependency injection framework only takes care of provide the dependencies where needed it does not connect the Component automatically in any way.

With Koin you can pass the Bundle during creation of fragment using a FragmentFactory.

val arguments = Bundle().apply { 
putString("key", "value")
}
supportFragmentManager.beginTransaction()
.replace(R.id.container, MyFragment::class.java, arguments)
.commit()

To pass data after the fragment created you have set it in Fragment somehow. There can be following options:-

  1. If you are using MVVM you can use a shared ViewModel to pass the data using LiveData.
  2. Alternatively you can get the Fragment from back stack and call a method on it.
  3. Or you can use a callback interface