Android Share Data Between Activity and Fragment Using ViewModel

July 10, 2019

Parent Activity

class ParentActivity : AppCompatActivity() {
    lateinit var viewModel: QuoteMakerXViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.parent)
        setSupportActionBar(toolbar)

        viewModel = ViewModelProviders.of(this).get(ParentViewModel::class.java)
        viewModel.testMessage = "Hello"

        viewModel.selectItemEvent.observe(this, Observer { event ->
            Timber.d("selectItemEvent=$event")
        })

        viewModel.sharedLiveData.observe(this, Observer { event ->
            Timber.d("sharedLiveData=$event")
        })
    }
}

Shared ViewModel

class ParentViewModel : ViewModel() {
    internal val selectItemEvent = SingleLiveEvent<String>()
    internal val sharedLiveData = MutableLiveData<String>()
    internal var testMessage: String? = null
}

NOTE: SingleLiveEvent is used to handle UI event.

Child Fragment

class ChildAFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.childa, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        viewModel = ViewModelProviders.of(activity!!).get(ParentViewModel::class.java)

        // shared message from parent
        Timber.d("viewModel.testMessage=%s", viewModel.testMessage)

        // send ui event back to parent
        button.setOnClickListener {
            viewModel.selectItemEvent.value = "ChildA button click"
        }

        // send data back to parent
        viewModel.sharedLiveData.value = "ChildA loaded"
    }
}

Could create another ChildBFragment where data/event could be shared between ParentActivity - ChildAFragment - ChildBFragment

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.