I created a Basic Views Activity in Android Studio and I cannot figure for the life of me how to change the “setOnClickListener” and icon of the FAB between fragments. I’m using the FAB to bring up a photo picker, once you choose a photo, it moves to the next fragment.
I’ve tried setting the Image Resource when moving to the next fragment which although feels hacky, it worked. But I can only make it revert using the toolbar back button using onSupportNavigateUp(), which again feels hacky. This makes it not revert with Android’s navigation back button. I’ve looked at similar answers and they also look so complicated. It navigation supposed be this hard? Or am I doing this totally wrong should be using activities for this project?
1
Extending my comment, I’m writing an answer with some code to give you an idea.
Activity
private val listener = NavController.OnDestinationChangedListener { controller, destination, arguments ->
// Check destination.id and change the FAB icon accordingly here
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// init views
fab.setOnClickListener {
val id = navController.currentDestination?.id
// check the id and perform the action accordingly
}
// rest of your code
}
override fun onResume() {
super.onResume()
controller.addOnDestinationChangedListener(listener)
}
override fun onPause() {
controller.removeOnDestinationChangedListener(listener)
super.onPause()
}