Wun
Wun

Reputation: 6381

How to get ViewModel in Activity in Android SunFlower Project?

I am studying MVVM of Google Android SunFlower project.

For Fragment, it gets viewmodel like the following

private val plantDetailViewModel: PlantDetailViewModel by viewModels {
        InjectorUtils.providePlantDetailViewModelFactory(requireActivity(), args.plantId)
    }

I want to try the same method to get viewmodel in Activity. but the requireActivity()show unresolved reference...

And the data binding is not working when I replace it to this.

Does it has other pattern can be use for providePlantDetailViewModelFactory()

Thanks in advance.

Upvotes: 4

Views: 759

Answers (3)

Ememobong AkpanEkpo
Ememobong AkpanEkpo

Reputation: 630

You have to add these to your build.gradle

implementation "androidx.core:core-ktx:1.3.1"
implementation "androidx.fragment:fragment-ktx:1.2.5"

Usage in Activity

val usersViewModel: UsersViewModel by viewModels()

Usage in Fragment

// Get a reference to the ViewModel scoped to this Fragment
val viewModel by viewModels<MyViewModel>()

// Get a reference to the ViewModel scoped to its Activity
val viewModel by activityViewModels<MyViewModel>()

Upvotes: 2

IgorGanapolsky
IgorGanapolsky

Reputation: 26841

You need a gradle dependency on "androidx.activity:activity-ktx:$version".

Then you can import androidx.activity.viewModels in your Activity.

Upvotes: 1

Jeel Vankhede
Jeel Vankhede

Reputation: 12138

I don't think so that you can do similar for your Activity that's done for Fragment.

Why?

The delegate function viewModels is available from fragment-ktx library (Refer here for reference) as extension for getting ViewModel instance lazily on your value objects using by keyword.

And there's no such thing available for Activities, for an instance.

So, better is to create your own or find some other way like basic lazy{} function from Kotlin standard library and providing logic to it.

Upvotes: -2

Related Questions