How to properly add options menu on a single fragment with navigation component without broke "up behavior"

If you're using setSupportActionBar, you must use setupActionBarWithNavController(), not toolbar.setupWithNavController as per the documentation.


if using toolbar do this: in Acitvity:

class MyActivity : AppCompatActivity() {
private var currentNavController: NavController? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_my)

    currentNavController = findNavController(R.id.settingNavHost)

    currentNavController?.let {
        val appBarConfiguration = AppBarConfiguration
            .Builder()
            .setFallbackOnNavigateUpListener {
                onBackPressed()
                true
            }.build()

        setSupportActionBar(toolbar)
        toolbar.setupWithNavController(it, appBarConfiguration)
    }
}

}

and in fragment:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    setHasOptionsMenu(true)
}

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    super.onCreateOptionsMenu(menu, inflater)
    inflater.inflate(R.menu.my_menu, menu)

}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    if (item.itemId == R.id.action_save) {
        saveInfo()
    }

    return super.onOptionsItemSelected(item)
}