asdheeraj / BottomNavigation

This project helps in understanding how to save the Fragment state by using the Bottom Navigation View
14 stars 8 forks source link

Load fragment on another fragment #2

Open talha01sayed opened 3 years ago

talha01sayed commented 3 years ago

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 }

Below is the code for onNavigationItemSelected

override fun onNavigationItemSelected(menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.home -> { loadFragment(mindOrksFragment) true } R.id.search -> { loadFragment(afterAcademyFragment) true } R.id.team -> { loadFragment(buddiesFragment) true } R.id.add -> { loadFragment(createFragment) true } R.id.profile -> { loadFragment(userFragment) true } else -> false } }

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) }}

talha01sayed commented 3 years ago

Sorry for the bad writing I hope you will respond