简体   繁体   中英

how to set background for menu item shown in actionBar

I am showing a menu item in the action bar. I would like to set a background for this item. I would prefer not to use an icon because otherwise I cannot use strings.xml for localization (I am showing some text in this particular menu item, that will get translated in several languages.).

Most of answers here suggest to use icons. The icon of course would cover the text, and if I try android:background instead of android:icon it just won't show anything.

So basically I want to customize the menu item in the actionbar with a custom image but at the same time be able to write something on it (pull some strings). Is there a way to this in xml?

PS I am using Theme.Holo.Light.DarkActionBar but I already changed the background of the actionbar.

As a workaround you could always have different icons for your localization. There is nothing stopping you having:

/drawable-fr/
/drawable-us/

On the other hand if you believe it is something to do with the Theme you are inheriting you could look through the source code for the DarkActionBar and then extend this in styles.xml overriding the values you want to change (the color of).

https://github.com/android/platform_frameworks_base/tree/master/core/res/res/values

Create an xml file per each icon you wan to show in the action bar in the 'drawable' directory like the one below:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/menuitem_bk"/>
    <item android:drawable="@drawable/icon_one"/>      
</layer-list>

Drawable icon_one is just the icon with a transparent background and 'menuitem_bk' will be a drawable defined as follows:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <size
        android:height="36dp"
        android:width="36dp" />
    <solid android:color="@color/action_bar_items_bk_color" />
</shape>

You will have to create four of these, one in each drawable directory (xhdpi, hdpi, mdpi and ldpi). The size of the shape will be different according to the directory:

  • xhdpi -> 48x48 hdpi -> 36x36 mdpi -> 24x24 ldpi -> 18x18

(Acording to this: http://developer.android.com/guide/practices/ui_guidelines/icon_design_action_bar.html )

And you got your ActionBar icons with background.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM