I am having some trouble getting an options menu working in Android. I have built apps before, and they all worked fine, but now the menu just doesn\'t pop up.
The c
If above answer doesn't work, make sure that you are using the same id of toolbar.
layout_app_bar.xml
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize">
activiy_main.xml
<include
android:id="@+id/app_bar"
layout="@layout/layout_app_bar" />
in java file:
don't call:
Toolbar tb = findViewById(R.id.toolbar);
please call:
Toolbar tb = findViewById(R.id.app_bar);
That is because the activity does not have the toolbar.
There are 2 steps in order to do it.
First, you need to add the toolbar in your activity.xml which is in res/layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"">
<!-- add this part-->
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Second, let your activity append it
in JAVA
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
or in Kotlin
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
In the latest versions of Android when using the compat library for toolbar, is very common that this happens, in order to get the menu items to display in the toolbar you must do the following:
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
I had the same issue. My problem was solved by inheritance of a different activity class.
So I had been doing:
public class WelcomeActivity extends Activity
but changed this to:
public class WelcomeActivity extends AppCompatActivity
This way I was saying that say an action bar can be added to your activity.
Call setHasOptionsMenu
function from onCreate
first. The onCreateOptionsMenu
will be automatically called.
Try this:
setHasOptionsMenu(true)
If the phone you test on has a menu button onCreateOptionsMenu wont't be called on start with the theme:
android:theme="@android:style/Theme.Black.NoTitleBar"
But when you click the menu button the onCreateOptionsMenu
will be called. I don't know what happens on phones without hardware buttons...