Make an Android button change background on click through XML

nbarraille picture nbarraille · Nov 8, 2010 · Viewed 149.1k times · Source

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?

Answer

David picture David · Nov 8, 2010

To change image by using code

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setImageResource(R.drawable.ImageName);
   }
}

Or, using an XML file:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <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 -->
</selector>

In OnClick, just add this code:

ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName));