Passing data between Fragments in the same Activity

前端 未结 7 1536
清歌不尽
清歌不尽 2021-02-09 12:01

Am working in a project with an Activity that host many fragments. Now I need to share some data (integers, strings, arraylist) between these fragments.

First time i use

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-09 12:44

    Use a SharedViewModel proposed at the official ViewModel documentation

    First implement fragment-ktx to instantiate your viewmodel more easily

    dependencies {
    implementation "androidx.fragment:fragment-ktx:1.2.2"
    }
    

    Then, you just need to put inside the viewmodel the data you will be sharing with the other fragment

    class SharedViewModel : ViewModel() {
        val selected = MutableLiveData()
    
        fun select(item: Item) {
            selected.value = item
        }
    }
    

    Then, to finish up, just instantiate your viewModel in each fragment, and set the value of selected from the fragment you want to set the data

    Fragment A

    class MasterFragment : Fragment() {
    
        private val model: SharedViewModel by activityViewModels()
    
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            itemSelector.setOnClickListener { item ->
            model.select(item)
          }
    
        }
    }
    

    And then, just listen for this value at your Fragment destination

    Fragment B

    class DetailFragment : Fragment() {
    
            private val model: SharedViewModel by activityViewModels()
    
            override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
                super.onViewCreated(view, savedInstanceState)
                model.selected.observe(viewLifecycleOwner, Observer { item ->
                    // Update the UI
                })
            }
        }
    

    This answer can help you, https://stackoverflow.com/a/60696777/6761436

提交回复
热议问题