Create a drawable xml file in res/drawable
such as res/drawable/button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed"
android:state_pressed="true" />
<item android:drawable="@drawable/button_normal" />
</selector>
where button_pressed
and button_normal
are just regular png files in one of your drawable directories (e.g/ drawables-hdpi
)
Then in your menu.xml or in your code you can refer to @drawable/button_selector
or R.drawable.button_selector
and the image will change automatically when the button is pressed.
If you need to change the ActionBar button background you need to override the theme in your res/values/style.xml
.
<style name="YourTheme.Sherlock" parent="@style/Theme.Sherlock">
<item name="actionBarItemBackground">@drawable/actionbar_item_background_selector</item>
<item name="android:actionBarItemBackground">@drawable/actionbar_item_background_selector</item>
</style>
Both lines matter: one for the SherlockActionBar and one for the standard ActionBar
Then set the theme to your activity in the manifest:
<activity
android:name=".yourActivity"
android:theme="@style/YourTheme.Sherlock" >
</activity>
And here is actionbar_item_background_selector.xml
to be placed in res/drawable
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Even though these two point to the same resource, have two states so the drawable will invalidate itself when coming out of pressed state. -->
<item android:state_focused="true" android:state_enabled="false" android:state_pressed="true" android:drawable="@drawable/scene_overlay_bar_pressed_center" />
<item android:state_focused="true" android:state_enabled="false" android:drawable="@drawable/abs__list_selector_disabled_holo_light" />
<item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/scene_overlay_bar_pressed_center" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/scene_overlay_bar_pressed_center" />
<item android:state_focused="true" android:drawable="@drawable/abs__list_focused_holo" />
<item android:drawable="@android:color/transparent" />
</selector>
replace the background with the drawable of your choice where android:state_pressed="true"
It's a lot to do for just a background but that is how the ActionBar
works.