Skip to content

Instantly share code, notes, and snippets.

@AmilcarM11
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmilcarM11/afbc5ab5a0cbc1ec545b to your computer and use it in GitHub Desktop.
Save AmilcarM11/afbc5ab5a0cbc1ec545b to your computer and use it in GitHub Desktop.
Android: Create a Switch toggle with custom icon thumb
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/bg_check_toggle_inactive" />
<item android:state_checked="true" android:drawable="@drawable/bg_check_toggle_active" />
<item android:drawable="@drawable/bg_check_toggle_inactive" />
</selector>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/ic_checktoggle_inactive" />
<item android:state_checked="true" android:drawable="@drawable/ic_check_toggle_active" />
<item android:drawable="@drawable/ic_checktoggle_inactive" />
</selector>
<?xml version="1.0" encoding="utf-8"?>
<Switch xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:thumb="@drawable/check_toggle_thumb"
style="@style/CheckToggle"
android:contentDescription="@string/action_check_consistency">
</Switch>
<dimen name="check_toggle_min_width">40dip</dimen>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MyActivity">
<item android:id="@+id/check_toggle"
app:showAsAction="always"
android:title="@string/action_check_consistency"/>
</menu>
private boolean mToggleState = false;
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Check toggle
MenuItem item = menu.findItem(R.id.check_toggle);
item.setActionView(R.layout.check_toggle_view);
Switch mSwitch = (Switch) item.getActionView();
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
onToggleStateChanged(isChecked);
}
});
super.onCreateOptionsMenu(menu, inflater);
}
private void onToggleStateChanged(boolean isChecked) {
mToggleState = isChecked;
// do something!
}
<style name="CheckToggle">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">fill_parent</item>
<item name="android:textOn"></item>
<item name="android:textOff"></item>
<item name="android:track">@drawable/check_toggle_background</item>
<item name="android:switchMinWidth">@dimen/check_toggle_min_width</item>
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment