Search code examples
androidkotlinviewmodelandroid-fragmentactivityandroid-viewmodel

How to set MainViewModel?


I have my MainActivity where there are the movie with their poster. If I click on a poster (in the layout there are 4 ImageView) I can read the plot (a TextView) that is in the Fragment. If I open my app with the emulator MainActivity and Fragment are overlapping so I need to set the ViewModel. How to set it?

//MainActivity

class JacksonActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.jackson_activity)
    if (savedInstanceState == null) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.jackson_film, JacksonFragment.newInstance())
            .commitNow()
    }
}

//Fragment

class JacksonFragment : Fragment() {

companion object {
    fun newInstance() = JacksonFragment()
}

private lateinit var viewModel: MainViewModel

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?,
): View {
    return inflater.inflate(R.layout.jackson_fragment, container, false)
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    viewModel = ViewModelProvider(this)[MainViewModel::class.java]
    // TODO: Use the ViewModel
} }

Solution

  • ViewModelProvider is deprecated. more info: ViewModelProvider

    To implement viewModel simply use val viewModel: MainViewModel by viewmodels()

    if you use the same viewmodel in more than one place(acitity/fragment) in fragment use val viewModel: MainViewModel by activityViewModels()

    Note: do not forget to update the dependencies. More info: ViewModel / SharedViewModel