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

后端 未结 2 780
日久生厌
日久生厌 2021-01-13 01:18

I\'m having some trouble to add options menu on a single fragment because it\'s breaking the navigation Up. Here my code

I have an single Activity with NoActio

相关标签:
2条回答
  • 2021-01-13 01:50

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

    0 讨论(0)
  • 2021-01-13 02:06

    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)
    }
    
    0 讨论(0)
提交回复
热议问题