How to set background of selected/unselected Button in the XML file How to set background of selected/unselected Button in the XML file xml xml

How to set background of selected/unselected Button in the XML file


If it's selected or not selected you should use a toggle button https://developer.android.com/reference/android/widget/ToggleButton.html

Be aware that there are still 4 states for that

You define them in a selector like this

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_checked="true" android:state_pressed="true" android:drawable="@drawable/likeactivepressed" />    <item android:state_pressed="true" android:drawable="@drawable/likeinitialpressed"/>    <item android:state_checked="true" android:drawable="@drawable/likeon"/>    <item android:drawable="@drawable/likeinitial"/></selector>

Then define it in your button like this

  android:background="@drawable/like_button"

Edit

You could actually just use 1 button for your use. Alternatively you can use 2 radio buttons

https://developer.android.com/reference/android/widget/RadioButton.html


This is used to change color of button on pressed or focusedwrite this code in your drawable folder

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"><!-- Button Focused-->    <item   android:state_focused="true"            android:state_pressed="false"            android:drawable="@drawable/login_hover"            /><!-- Button Focused Pressed-->    <item   android:state_focused="true"            android:state_pressed="true"            android:drawable="@drawable/login_hover"            /><!-- Button Pressed-->    <item   android:state_focused="false"            android:state_pressed="true"            android:drawable="@drawable/login_hover"            /><!-- Button Default Image-->    <item   android:drawable="@drawable/login_bg"/></selector

http://nishantvnair.wordpress.com/2010/10/05/change-color-of-button-on-click-android/


To change background image:

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));