Search code examples
androidandroid-actionbar

Set icon and back button on action bar at same time in Android


getSupportActionBar().setIcon(R.drawable.icon); is not working in Android.

    getSupportActionBar().setTitle("Dictionary");
    getSupportActionBar().setDisplayUseLogoEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true); 
    getSupportActionBar().setIcon(R.drawable.ic_dictionary);

Solution

  • in your case you should have a line of code before these lines...if you dont have this line that is the problem

    setSupportActionBar(toolbar);
    

    however i myself use material toolbar and add icon and text to toolbar in xml and got rid of these methods! see one of my xml files for sample

    <com.google.android.material.appbar.AppBarLayout
        android:background="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    
        <com.google.android.material.appbar.MaterialToolbar
            android:layout_width="match_parent"
            android:layout_height="?actionBarSize">
    
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
    
                <ImageView
                    android:id="@+id/iv_back"
                    android:onClick="onClick"
                    android:layout_width="wrap_content"
                    android:padding="16dp"
                    android:background="@drawable/ripple_on_primary"
                    android:layout_centerVertical="true"
                    android:layout_alignParentEnd="true"
                    android:src="@drawable/ic_back"
                    android:layout_height="wrap_content"/>
    
                <TextView
                    android:layout_centerVertical="true"
                    android:layout_toStartOf="@id/iv_back"
                    android:id="@+id/tv_toolbar"
                    style="@style/tvTitle"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/previous_transactions" />
    
                <TextView
                    style="@style/tvContent"
                    android:text="@string/help"
                    android:id="@+id/tv_help"
                    android:onClick="onClick"
                    android:layout_centerVertical="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>
    
            </RelativeLayout>
    
        </com.google.android.material.appbar.MaterialToolbar>
    
    </com.google.android.material.appbar.AppBarLayout>