Menu

Toolbar

  • Toolbar makes it easy to set up an app bar that works on a wide range of devices.

  • Toolbar gives you room to customize your app bar later, as your app develops.

  • Toolbar includes the most recent features, and it works for any device that can use the support library.

Adding toolbar in layout

<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:title="@string/app_name"
    app:titleTextColor="#fff"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

java

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

change theme

styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

menu layout file

menu_main.xml
<?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/action_settings"
        android:orderInCategory="100"
        android:title="Settings"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_favorites"
        android:icon="@drawable/ic_favorite_border_black_24dp"
        android:orderInCategory="40"
        android:title="fav"
        app:showAsAction="ifRoom" />
</menu>

Initialize menu

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

Menu click listener

MainActivity.java
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            Toast.makeText(this, "settings", Toast.LENGTH_SHORT).show();
            return true;
        case R.id.action_favorites:
            Toast.makeText(this, "favourites", Toast.LENGTH_SHORT).show();
            return true;
        default:
            // Do nothing
    }
    return super.onOptionsItemSelected(item);
}

Last updated