Java – How do I access the default toolbar from Activities in Android?

How do I access the default toolbar from Activities in Android?… here is a solution to the problem.

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 SupportActionBarit like this:

supportActionBar?.title = "My Activity title"

This code:Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); Only if you use 添加了 Toolbar 时才有效xml 中的工具栏 id. Even if you do, you should do anything beforesetSupportActionBar(yourToolBar) doing anything. Then use supportActionBarit directly.

Related Problems and Solutions