Take the 2-minute tour ×

Is there a way to specify an alternative background image/color for a Button in the XML file that is going to be applied onClick, or do I have to do a Button.setBackground() in the onClickListener?

share|improve this question
For more details and implementation help refer to the android docs. –  Pinhassi Aug 11 '11 at 7:27

3 Answers 3

up vote 74 down vote accepted

To change image by using code

public void onClick(View v) {
   if(v == ButtonName) {

Or, using an XML file:

  <item android:state_pressed="true"
   android:drawable="@drawable/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->

In OnClick, just add this code:

share|improve this answer
Thanks, exactly what I was looking for (the item state thing...) –  nbarraille Nov 8 '10 at 16:46
@David,thanks for this post.i have couple of image buttons require this feature(change image on pressed) what are changes needed in Selector & onClick for all? can you guide me? –  RDC Jun 2 '12 at 7:47
where exactly do you point to that xml file in the second approach? –  Paul Jun 13 '12 at 14:30
setBackgroundDrawable is now deprecated.. –  Amyth Jul 21 '12 at 5:02
@Paul in the second approach put the xml file in the drawable folder and in the ImageView you want to use just set android:src="@drawable/xmlfile" –  jaxvy Aug 29 '12 at 8:58

In the latest version of the SDK, you would use the setBackgroundResource method.

public void onClick(View v) {
   if(v == ButtonName) {
share|improve this answer
Thanks a bunch for this updated answer –  Darrell Aug 18 at 14:33


public void onclick(View v){
            ImageView activity= (ImageView) findViewById(R.id.imageview1);
share|improve this answer

Your Answer


