简体   繁体   中英

How to change the background color of an icon in the action bar, when clicked?

The solution provided here doesnt work for me because it requires api14 and I want to support earlier verions:

Change action background color when selected (ActionBarSherlock)

Right now when I tap an item on the action bar with my finger it turns blue and I dont want that to happen.

Information: I'm using SherlockActionBar.

and this doesnt work because it requires api11:

        ImageView icon = (ImageView) findViewById(android.R.id.home);
        icon.setBackgroundColor(getResources().getColor(R.color.black));

Here is my action_bar_items.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/abFeed"
        android:icon="@drawable/ic_action_content_paste"
        android:title="@string/abFeed"
        android:showAsAction="always"/>
    <item
        android:id="@+id/abNotifications"
        android:icon="@drawable/ic_action_social_cc_bcc"
        android:title="@string/abNotifications"
        android:showAsAction="always"/>
    <item
        android:id="@+id/abAddNewItem"
        android:icon="@drawable/ic_action_content_new"
        android:title="@string/abAddNewItem"
        android:showAsAction="always"/>
    <item
        android:id="@+id/abSearch"
        android:icon="@drawable/ic_action_action_search"
        android:title="@string/abSearch"
        android:showAsAction="always"/>
</menu>

EDIT: Here is what helped me solve the issue, thanks to Mario Lenci:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@FF000000" /> <!-- pressed -->
<item android:drawable="@android:color/transparent" /> <!-- default -->
</selector>

and in styles:xml

<style name="Theme.SherlockCustom" parent="@style/Theme.Sherlock.Light">
    <item name="actionBarItemBackground">@drawable/action_bar_item_background</item>
    <item name="android:icon">@android:color/transparent</item>
    <item name="android:minWidth">0dp</item>
    <item name="android:padding">0dp</item>
</style>

you have to set this attribute in your application/Activity main Theme

<item name="android:actionBarItemBackground">@drawable/your_drawable</item>

with action bar sherlok you also have to set

<item name="actionBarItemBackground">@drawable/your_drawable</item>

you can find a good documentation on ActionBar styling here

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