You can use a selector defining images for both states, when pressed and normal:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/btnOn"/>
<item android:state_pressed="false" android:drawable="@drawable/btnOff"/>
</selector>
This selector is stored in the folder /drawable
and you send it in your ImageButton
through the property android:src
:
<ImageButton android:src="@drawable/image_selector"
...
/>
Another option is to change the image by pressing the ImageButton
, for example assuming having 2 images within /drawable
calls btnOff.png and btnOn.png, when detecting whether the button is pressed or not, we determine to change the images by:
imageButton.setImageResource()
Example:
final ImageButton imageButton = (ImageButton)findViewById(R.id.imageButton);
imageButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_UP){
imageButton.setImageResource(R.drawable.btnOff);
return true;
}else if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
imageButton.setImageResource(R.drawable.btnOn);
return true;
}
return false;
}
});
Application where both options are shown:
link