# Menu

![](https://111087263-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-L_Lt0fyRsHcS_4ZagFx%2F-La-6fxhsrMwfczGcsH5%2F-La-72bbuzl4TyF484n9%2Fdg_appbar_annotated.png?alt=media\&token=e058a4e9-80ea-4eaf-aae4-8a472aa418f2)



### **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**

```markup
<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**

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

**change theme**

{% code title="styles.xml" %}
```markup
<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>
```
{% endcode %}

**menu layout file**

{% code title="menu_main.xml" %}
```markup
<?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>
```
{% endcode %}

**Initialize menu**

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

**Menu click listener**

{% code title="MainActivity.java" %}
```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);
}
```
{% endcode %}
