Adding icon in Android ToolBar
Asked Answered
M

2

6

I have two activities

  • MainActivity
  • DetailActivity

My MainActivity.xml has AppBarLayout and Toolbar elements. In Main Activity.java, I set the icon in toolbar using:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// setting icon
getSupportActionBar().setIcon(R.mipmap.ic_launcher);

This same line of code is not working for Detail activity. Detail Activity has the toolbar by default. I can set the title in toolbar as well using:

getSupportActionBar().setTitle(String title);

But, I am unable to set Icon in Detail Activity using:

getSupportActionBar().setIcon(R.mipmap.ic_launcher);

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:name=".App"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".apod_main"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".apod_detail"></activity>
</application>

Build Configs:

Android API 26
Build Tools Version 26.0.1

Municipalize answered 23/8, 2017 at 8:22 Comment(0)
E
12

Try this:

getSupportActionBar().setDisplayShowTitleEnabled(true);  
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
Elegist answered 23/8, 2017 at 8:27 Comment(4)
Thank You! This worked for me. getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setIcon(R.mipmap.ic_launcher);Municipalize
Be aware that getSupportActionBar().setDisplayShowHomeEnabled(boolean); might produce NullPointerException preform null checking before using it.Brisco
@Yupi, to avoid the null pointer exception, place the commands in the onPrepareOptionsMenu method.Magnoliamagnoliaceous
And how we can add click listener into this icon?Gusman
C
3

try this if you want to add back arrow in your actionbar

getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher)
Checkrein answered 23/8, 2017 at 8:36 Comment(1)
(Oct 2020) Because I want to add my app icon instead of back arrow, I had to add as the very first line getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_launcher); before these 2 lines; the last line was not needed then.Tried

© 2022 - 2024 — McMap. All rights reserved.