Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Options Menu with custom actionbar/toolbar view

I have already implemented a custom view for my actionbar. Along with that, I also need an OptionMenu. Is there any way to still use the default OptionMenu? I dont want to design the entire menu & its functionality myself.

BTW, my activity extends android.support.v7.app.AppCompatActivity


Code to implement custom view for my actionbar

custom_action_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentInsetEnd="0dp"
app:contentInsetStart="0dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/custom_B"
        android:layout_width="60dp"
        android:layout_height="30dp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>

I included it in my main XML:

<include
layout="@layout/custom_action_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

For OptionsMenu I put some logs which are never printed

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    Log.i(Constants.APP_NAME, "hello1");
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Log.i(Constants.APP_NAME, "hello2");
}
like image 759
Pranav Mahajan Avatar asked Oct 17 '22 23:10

Pranav Mahajan


1 Answers

Don't forget to call setSupportActionBar() in your activity.

Without this call, the associated menu methods are never called because the Activity considers that there is no Toolbar.

like image 121
JDenais Avatar answered Oct 21 '22 05:10

JDenais