Search code examples
androidandroid-studioandroid-fragmentsandroid-toolbar

Toolbar fragment onoptionsitemselected not called kotlin, several solutions what is the recomended?


I got lost trying to control onclick for options menu in fragments. There are so many solutions that I don't even know where to start.

I saw some places where people tell us to use NavController, others tell us to use onOptionsItemSelected both in the activity and fragment and override what you need. On top of that we have the androidx.appcompat.widget.Toolbar that doesn't even need to be inflated, just use app:menu= in the XML file and boom all there but how do I listen to the clicks ?

<androidx.appcompat.widget.Toolbar
            app:menu="@menu/menu_fragment_main">

I had it working in the activity but then had to use fragments instead and got into this mess, I just want the menu to work like it was working in the activity.


Solution

  • val toolbar = fragmentInflater.findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbarMainActivity)
            (activity as AppCompatActivity).setSupportActionBar(toolbar)
    

    This solved the problem, kind of tired now but I well come comments on why this happened latter.

    I think it was some mix of , toolbar in xml, androidx, wrong imports for toolbar non android x and so on.