Sir, How can I load a fragment on another fragment? I have many fragments in my application and I want to load fragments dynamically. Can you please help me?
Below is the code for load fragment
private fun loadFragment(fragment: Fragment) {
fragmentManager.beginTransaction().hide(activeFragment).show(fragment).commit()
activeFragment = fragment
}
This is the code in oncreate method
fragmentManager.beginTransaction().apply { add(R.id.fragment_container, userFragment, "User").hide(userFragment) add(R.id.fragment_container, afterAcademyFragment, "Search").hide(afterAcademyFragment) add(R.id.fragment_container, buddiesFragment, "Buddies").hide(buddiesFragment) add(R.id.fragment_container,createFragment,"create").hide(createFragment) add(R.id.fragment_container, mindOrksFragment, "Home") }.commit()
I am using viewmodel to load fragment
viewModel.current.observe(this, { s: Fragment -> fragmentManager.beginTransaction().add(R.id.fragment_container,s,"Dynamic") fragmentManager.beginTransaction().hide(activeFragment).show(s).commitAllowingStateLoss() })
This is my code from bottom nav fragment
binding.settingIcon.setOnClickListener { viewModelActivity.changeFragment(SettingsFragment()) }
class MainViewModel : ViewModel() { val current = MutableLiveData<Fragment>() fun changeFragment(fragment: Fragment) { current.postValue(fragment) }}
Sir, How can I load a fragment on another fragment? I have many fragments in my application and I want to load fragments dynamically. Can you please help me? Below is the code for load fragment
Below is the code for onNavigationItemSelected
This is the code in oncreate method
fragmentManager.beginTransaction().apply { add(R.id.fragment_container, userFragment, "User").hide(userFragment) add(R.id.fragment_container, afterAcademyFragment, "Search").hide(afterAcademyFragment) add(R.id.fragment_container, buddiesFragment, "Buddies").hide(buddiesFragment) add(R.id.fragment_container,createFragment,"create").hide(createFragment) add(R.id.fragment_container, mindOrksFragment, "Home") }.commit()
I am using viewmodel to load fragment
viewModel.current.observe(this, { s: Fragment -> fragmentManager.beginTransaction().add(R.id.fragment_container,s,"Dynamic") fragmentManager.beginTransaction().hide(activeFragment).show(s).commitAllowingStateLoss() })
This is my code from bottom nav fragment
binding.settingIcon.setOnClickListener { viewModelActivity.changeFragment(SettingsFragment()) }
class MainViewModel : ViewModel() { val current = MutableLiveData<Fragment>() fun changeFragment(fragment: Fragment) { current.postValue(fragment) }}