Update (2008-10-29):
I just saw this on android-developers mailing list. Looks like it's a easier way to achieve this effect. (I haven't have time to test it myself).
from:
http://groups.google.com/group/android-developers/tree/browse_frm/thread/1906f24707594f67/17322a04f7af1a5b
In res/drawable, create a file called for instance mybutton_background.xml
and put something like this inside:
<?xml version="1.0" encoding="utf-8"?>
<selector android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="false"
android:drawable="@drawable/button_background_focus" />
<item android:state_focused="true" android:state_pressed="true"
android:drawable="@drawable/button_background_pressed" />
<item android:state_focused="false" android:state_pressed="true"
android:drawable="@drawable/button_background_pressed" />
<item drawable="@drawable/button_background_normal">
</selector>
Then set this drawable as the background of your button with
android:background="@drawable/mybutton_background"
This is not documented anywhere in the android site.
==============================================================
The standard Button widget in Android has an onpress effect which will paint the button with orangish color when the button is pressed. However, if you change the background of the button widget to create your own custom button, the onpressed effect will be lost.
To create the same effect with your custom button image, you need to extend the Button class and override its onDraw() methd as followed:
public class OnPressButton extends Button{Then instead of using the Button widget, use the above implementation of Button in your layout xml file.
public OnPressButton(Context context) {
super(context);
}
public OnPressButton(Context context, AttributeSet attrs){
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
//sets the button image based on whether the button in its pressed state
setBackgroundDrawable(getResources().getDrawable(isPressed()?R.drawable.btn_on : R.drawable.btn_off));
super.onDraw(canvas);
}
}
<view
class="com.mycompany.android.ui.OnPressButton"
android:background="@android:color/transparent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="My Button" />
Observe that the background is set to "color/transparent".
That's all you need to do to implement the onpress effect. For more details about implementing custom widget, see also http://code.google.com/android/toolbox/custom-components.html