Morozov
Morozov

Reputation: 5250

How to call the newInstance method correctly?

In my first fragment i write next code:

viewModel.showConnectionsSelectorFragmentEvent.observe(this, Observer<List<ConnectionViewModel>> {
    val selectConnectionsFragment = SelectConnectionsFragment()
    selectConnectionsFragment.setTargetFragment(this, 555)
    activity?.addFragment(SelectConnectionsFragment.newInstance(connections = it))
})

And here is the problem, idk how to call newInstance from my val selectConnectionsFragment. in my fragment for newInstance i have next code and it works fine:

companion object {
    const val KEY_CONNECTIONS = "CONNECTIONS"

    fun newInstance(connections: List<ConnectionViewModel>): SelectConnectionsFragment {
        val arrayList = ArrayList<ConnectionViewModel>(connections)
        return SelectConnectionsFragment().apply {
            arguments = Bundle().apply {
                putSerializable(KEY_CONNECTIONS, arrayList)
            }
        }
    }
}

Upvotes: 0

Views: 47

Answers (1)

Sergio
Sergio

Reputation: 30655

If I understand correctly you can just call SelectConnectionsFragment.newInstance(...) and assign it to selectConnectionsFragment:

viewModel.showConnectionsSelectorFragmentEvent.observe(this, Observer<List<ConnectionViewModel>> {
    val selectConnectionsFragment = SelectConnectionsFragment.newInstance(connections = it)
    selectConnectionsFragment.setTargetFragment(this, 555)
    activity?.addFragment(selectConnectionsFragment)
})

Upvotes: 3

Related Questions