Monday, January 18, 2016

Add OptionsMenu to Toolbar


Modify from last example of "Set title, subtitle and logo of Toolbar", to add OptionsMenu to Toolbar.


Create /res/menu/menu_main.xml to define our OptionsMenu.
<?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/menu_camera"
        android:icon="@android:drawable/ic_menu_camera"
        android:orderInCategory="100"
        android:title="camera"
        app:showAsAction="always"/>
    <item
        android:id="@+id/menu_compass"
        android:icon="@android:drawable/ic_menu_compass"
        android:orderInCategory="100"
        android:title="compass"
        app:showAsAction="always"/>
    <item
        android:id="@+id/menu_agenda"
        android:icon="@android:drawable/ic_menu_agenda"
        android:orderInCategory="100"
        android:title="agenda"
        app:showAsAction="always"/>
    <item
        android:id="@+id/menu_gallery"
        android:icon="@android:drawable/ic_menu_gallery"
        android:orderInCategory="100"
        android:title="gallery"
        app:showAsAction="always"/>
    <item
        android:id="@+id/menu_calendar"
        android:icon="@android:drawable/ic_menu_my_calendar"
        android:orderInCategory="100"
        android:title="calendar"
        app:showAsAction="always"/>
</menu>

Modify MainActivity.java, override onCreateOptionsMenu() and onOptionsItemSelected().
package com.blogspot.android_er.androidtoolbar;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setTitle("Toolbar example");
        toolbar.setSubtitle("Android-er.blogspot.com");
        toolbar.setLogo(android.R.drawable.ic_menu_info_details);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Toast.makeText(this, item.getTitle(), Toast.LENGTH_LONG).show();
        return super.onOptionsItemSelected(item);
    }
}


Next:
Set image on Toolbar

No comments: