我可以使用styles.xml来设置我的ActionBar的主页图标吗?

14

我在我的应用程序中使用以下代码将我的主页图标设置为特定的Drawable:

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

但是我在根据Jake Wharton的解释(在这里)ActionBar Lag in hiding title时,遇到了“创建装饰视图和我的onCreate执行之间”的“滞后”问题。

在上面的链接中,解决方案是创建一个新样式,并在清单中声明它,因此我也这样做了:

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

清单文件:

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

现在它已经正常工作了,我拥有了我的主页按钮与向上配置,但我仍然想在此活动中将图标更改为另一个特定的可绘制对象,而不必更改清单中的任何android:icon。我该如何实现?

希望这足够清晰明了。谢谢。

1个回答

28

好的,我弄清楚少了什么了。在styles.xml中,我只需要添加以下几行:

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

所以最终我有了这样的东西:

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

现在它完美地运行,所有的displayOptions都正确设置,并且没有“延迟”。


谢谢,RenanFerrari。正是我想要的。 - BruceHill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接