Search code examples
javaandroidandroid-activitykotlintoolbar

How do I access the default ToolBar from an Activity in Android?


I'm trying to access the default ToolBar from within and Activity's onCreateOptionsMenu function to change the Overflow menu icon (three dots icon). I want to use the setOverflowIcon method provided by this class.

I have read the official documentation, posts on StackOverflow and other websites and everything fails.

I tried for example Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); but I get an error that says that R.id.toolbar doesn't exist.


Solution

  • If you're using AppcompatActivity, you should use SupportActionBar like this:

    supportActionBar?.title = "My Activity title"
    

    this piece of code: Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); only works when you've added a Toolbar with toolbar id in xml. even if you did it, you should setSupportActionBar(yourToolBar) before doing anything. Then use supportActionBar directly instead.