Search code examples
javaandroidxmltoolbar

Add icon to Toolbar in Android


I'm trying to add an icon, which is located into my drawable directory, to the right of my toolbar, right before the classic "vertical three dots". This is my xml:

<RelativeLayout 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="match_parent">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/my_toolbar"
        style="@style/HeaderBar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/_20sdp"
        android:layout_alignParentTop="true"
        android:layout_marginTop="@dimen/_3sdp">

        <item
            android:id="@+id/miCompose"
            android:icon="@drawable/eraser"
            android:title="Compose"
            app:showAsAction="ifRoom"></item>
    </androidx.appcompat.widget.Toolbar>

    <TextView
        android:id="@+id/textList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/my_toolbar"
        android:layout_centerHorizontal="true"
        android:textSize="26dp" />

    <ListView
        android:id="@+id/android:list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/my_toolbar" />

</RelativeLayout>

The problem is that I get this error on the line

android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class item

This is the style I would like to recreate in my app: enter image description here


Solution

  • Yes. You can use icon in menu method

    set Support Action Bar

      setSupportActionBar(toolbar)
    
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
            val inflater = menuInflater
            inflater.inflate(R.menu.menu_logout, menu)
            return true
        }