Calling setSupportActionBar
and inflating a menu as follows results in not showing the menu:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(myToolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
myToolbar.inflateMenu(R.menu.my_menu)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/myToolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/test"
android:title="Test"
app:showAsAction="always" />
</menu>
I know the alternative is to use the traditional onCreateOptionsMenu
method.
Other alternative is to remove the line setSupportActionBar
, but I need to show displayHomeAsUpEnabled.
Is it possible to use both myToolbar.inflateMenu()
and setSupportActionBar
simultaneously or is it incompatible?
When you use setSupportActionBar()
, yes, you must solely use the ActionBar APIs and directly manipulating the Toolbar, be it by adding a Menu or other changes, are not supported.
If you don't want to use the ActionBar APIs, then don't call setSupportActionBar
and use the Toolbar APIs directly (those are what the ActionBar APIs call anyways, so the Toolbar APIs are a superset of the ActionBar APIs already).
Toolbars have their own APIs for handling the navigation button (which is what displayHomeAsUpEnabled
plugs into).
You can take advantage of this by adding the Up icon to your Toolbar:
<androidx.appcompat.widget.Toolbar
android:id="@+id/myToolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navigationIcon="?attr/homeAsUpIndicator" />
Then you can get a callback on when the button is pressed by setting a click listener:
myToolbar.setNavigationOnClickListener {
// handle the navigation button
}