How to create a toggle button with custom image and no text in Android

Standard

Create a file ic_toggle.xml in your res/drawable folder

<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item
 android:state_checked="false"
 android:drawable="@drawable/ic_slide_switch_off" />
 <item
 android:state_checked="true"
 android:drawable="@drawable/ic_slide_switch_on" />
</selector>

Here @drawable/ic_slide_switch_on & @drawable/ic_slide_switch_off are images you create.

Then create another file in the same folder, name it ic_toggle_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+android:id/background" 
 android:drawable="@android:color/transparent" />
<item android:id="@+android:id/toggle"
 android:drawable="@drawable/ic_toggle" />
</layer-list>

Now add to your custom theme, (if you don’t have one create a styles.xml file in your res/values/folder)

<style name="Widget.Button.Toggle" parent="android:Widget">
 <item name="android:background">@drawable/ic_toggle_bg</item>
 <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
</style>

<style name="toggleButton" parent="@android:Theme.Black">
<item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
<item name="android:textOn"></item>
<item name="android:textOff"></item>

This creates a custom toggle button for you.
Now use the custom style and background in your view.

<ToggleButton
 android:id="@+id/toggleButton"
 android:layout_width="wrap_content"
 android:layout_height="match_parent"
 android:layout_gravity="right"
 style="@style/toggleButton"
 android:background="@drawable/ic_toggle_bg"
 />

Supporting Multiple Screens Using Drawables Different Density

Standard

Android supports several configuration qualifiers that allow you to control how the system selects your alternative resources based on the characteristics of the current device screen. A configuration qualifier is a string that you can append to a resource directory in your Android project and specifies the configuration for which the resources inside are designed.

setCompoundDrawables() doesn’t display the Button Drawable

Standard

Image is blank because it hasn’t got specified bounds. You may use setCompoundDrawables() but before you should specify image’s bounds, using Drawable.setBounds() method:

Drawable d = getResources().getDrawable(R.drawable.ic_action_selector);
d.setBounds(0, 0, 128, 128);
btnRegistery.setCompoundDrawables(null, d, null, null);