I have successfully implemented Bottom Navigation View but whenever the navigate from one fragment to another the first fragment gets completely destroyed even when i'm on the same fragment and press the menu button for it it gets destroyed
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.ncapdevi.fragnav.FragNavController
import com.shivam.spaced.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity(), FragNavController.RootFragmentListener {
private lateinit var binding: ActivityMainBinding
private var selectedFragment: Fragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.bottomNavigation.setOnNavigationItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.home_item -> {
selectedFragment = HomeFragment()
}
R.id.notification_item -> {
selectedFragment = NotificationsFragment()
}
R.id.camera_item -> {
selectedFragment = CameraFragment()
}
R.id.settings_item -> {
selectedFragment = SettingsFragment()
}
}
selectedFragment.id
if (selectedFragment != null) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, selectedFragment!!).commit()
}
return@setOnNavigationItemSelectedListener true
}
}
}
supportFragmentManager
.beginTransaction()
.add(R.id.fragment_container, selectedFragment!!)
.commit()
Transition.add
function adds a fragment to a container and Transition.replace
function removes the current container's fragment and add a new to it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.