Renan Ferrari
Renan Ferrari

Reputation: 2519

Can I set the home icon of my actionbar using styles.xml?

I was using the following code on my application to set my home icon to a specific drawable:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_menu);
getSupportActionBar().setDisplayShowTitleEnabled(false);

But I was having problems with the "lag" between "creating the decor view and my onCreate executing" as explained here by Jake Wharton: ActionBar Lag in hiding title

On the link above the solution was to create a new style, and declare it in the Manifest, and so I did:

<resources>
<style name="AppTheme" parent="android:Theme.Light" />

<style name="WATheme" parent="Theme.Sherlock.Light">
    <item name="android:actionBarStyle">@style/WATheme.ActionBar</item>
    <item name="actionBarStyle">@style/WATheme.ActionBar</item>
</style>

<style name="WATheme.ActionBar" parent="Widget.Sherlock.Light.ActionBar.Solid">
    <item name="android:displayOptions">homeAsUp|showHome</item>
    <item name="displayOptions">homeAsUp|showHome</item>
</style>
</resources>

Manifest:

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:theme="@style/WATheme"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

It is now working fine, I have my home button with up configuration, but I still want to change the icon to another specific drawable, only in this activity, without having to change any android:icon in the Manifest. How can I achieve that?

Hope it was clear enough. Thank you.

Upvotes: 14

Views: 14214

Answers (1)

Renan Ferrari
Renan Ferrari

Reputation: 2519

Ok, just figure it out what was missing. On styles.xml, all I had to do is to add the following lines:

<item name="android:icon">@drawable/ic_menu</item>
<item name="icon">@drawable/ic_menu</item>

So at the end I have something like this:

<resources>
<style name="AppTheme" parent="android:Theme.Light" />

<style name="WATheme" parent="Theme.Sherlock.Light">
    <item name="android:actionBarStyle">@style/WATheme.ActionBar</item>
    <item name="actionBarStyle">@style/WATheme.ActionBar</item>
    <item name="android:icon">@drawable/ic_menu</item>
    <item name="icon">@drawable/ic_menu</item>
</style>

<style name="WATheme.ActionBar" parent="Widget.Sherlock.Light.ActionBar.Solid">
    <item name="android:displayOptions">homeAsUp|showHome|showTitle</item>
    <item name="displayOptions">homeAsUp|showHome|showTitle</item>
</style>
</resources>

It works just fine now, with all displayOptions correctly set and with no "lags". :)

Upvotes: 28

Related Questions