Search code examples
androidandroid-fragmentskotlinandroid-actionbarandroid-toolbar

setSupportActionBar inside of a Fragment


I have a Fragment:

class HomeFragment : Fragment() { ... }

Now I'm trying to add an Actionbar to it, but this doesn't work:

setSupportActionBar(findViewById(R.id.toolbar_main))

How can I set the Support and then add Items to the ActionBar?

This is how it works in an AppCompatActivity:

//    This adds items to the ActionBar
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_toolbar_main, menu)
        return true
    }


//    This is the OnClickListener for the Buttons in the ActionBar
    override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
    R.id.toolbar_edit -> {


        true
    }

    R.id.toolbar_search -> {


        true
    }

    else -> {
        // If we got here, the user's action was not recognized.
        // Invoke the superclass to handle it.
        super.onOptionsItemSelected(item)
    }
}

Big thanks in advance!


Solution

  • Override onCreateOptionsMenu in your Fragment and inflate your menu inside. Than in onCreate method of Fragment set setHasOptionsMenu() to true. To inflate different menus depending on Fragment creation clear the menu first.

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }
    
    override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater?.inflate(Your menu here, menu)
    }