ViewPager2/Tabs problem with ViewModel state
new ViewModelProvider(requireActivity()).get("your_key", YourViewModel.class)
Use requireActivity to obtain a ViewModel not the fragment.
As per your comment, you are using Fragment and inside that Fragment there is your viewpager. So while creating your Adapter for ViewPager you need to pass childFragmentManager instead of getActivity()
Below is a sample Adapter for your viewPager that you can use
class NewViewPagerAdapter(fm: FragmentManager, behavior: Int) : FragmentStatePagerAdapter(fm, behavior) {
private val mFragmentList: MutableList<Fragment> = ArrayList()
private val mFragmentTitleList: MutableList<String> = ArrayList()
override fun getItem(position: Int): Fragment {
return mFragmentList[position]
}
override fun getCount(): Int {
return mFragmentList.size
}
fun addFragment(fragment: Fragment, title: String) {
mFragmentList.add(fragment)
mFragmentTitleList.add(title)
}
override fun getPageTitle(position: Int): CharSequence? {
return mFragmentTitleList[position]
}
}
and while creating your adapter call it like
val adapter = NewViewPagerAdapter(
childFragmentManager,
FragmentPagerAdapter.POSITION_UNCHANGED
)
as if you see the documentation for FragmentStatePagerAdapter it states that you should pass (FragmentManager, int) inside your adapter's constructor
I hope this will solve your issue as I was facing the same issue one day.
Happy coding.