How do I access the default toolbar from Activities in Android?
I’m trying to access the default ToolBar from inside and the activity’s onCreateOptionsMenu function to change the overflow menu icon (three-dot icon). I want to use the setOverflowIcon method provided by this class.
I’ve read the official documentation, posts on StackOverflow, and other sites, but everything has failed.
For example, I tried Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); But I get an error message stating that R.id.toolbar doesn’t exist.
Best Solution
If you are using AppcompatActivity
, you should use SupportActionBar
it like this:
supportActionBar?.title = "My Activity title"
This code:Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Only if you use 添加了
id. Even if you do, you should do anything beforeToolbar
时才有效xml
中的工具栏setSupportActionBar(yourToolBar)
doing anything. Then use supportActionBar
it directly.