Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an Android button change background on click through XML

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?

like image 794
nbarraille Avatar asked Nov 08 '10 16:11

nbarraille


People also ask

How can change background color of button in Android XML?

To set Android Button background color, we can assign android:backgroundTint XML attribute for Button in layout file with the required Color Value. To programmatically set or change Android Button background color, we may call pass the method Button.

What is selector in Android XML?

<selector> and <item> are used when you are creating a custom button. The <selector> tag is the root tag and it can contain multiple <item> tags, the only attribute it contains is the xmlns:android .


2 Answers

To change the image by using code:

public void onClick(View v) {    if(v.id == R.id.button_id) {      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)); 
like image 115
David Avatar answered Oct 13 '22 11:10

David


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

public void onClick(View v) {    if(v == ButtonName) {      ButtonName.setBackgroundResource(R.drawable.ImageResource);    } } 
like image 41
cdrev Avatar answered Oct 13 '22 12:10

cdrev