to top
Android APIs
public class

Switch

extends CompoundButton
java.lang.Object
   ↳ android.view.View
     ↳ android.widget.TextView
       ↳ android.widget.Button
         ↳ android.widget.CompoundButton
           ↳ android.widget.Switch

Class Overview

A Switch is a two-state toggle switch widget that can select between two options. The user may drag the "thumb" back and forth to choose the selected option, or simply tap to toggle as if it were a checkbox. The text property controls the text displayed in the label for the switch, whereas the off and on text controls the text on the thumb. Similarly, the textAppearance and the related setTypeface() methods control the typeface and style of label text, whereas the switchTextAppearance and the related seSwitchTypeface() methods control that of the thumb.

See the Toggle Buttons guide.

Summary

XML Attributes
Attribute Name Related Method Description
android:switchMinWidth setSwitchMinWidth(int) Minimum width for the switch component

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". 

android:switchPadding setSwitchPadding(int) Minimum space between the switch and caption text

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". 

android:switchTextAppearance setSwitchTextAppearance(Context,int) TextAppearance style for text displayed on the switch thumb. 
android:textOff setTextOff(CharSequence) Text to use when the switch is in the unchecked/"off" state. 
android:textOn setTextOn(CharSequence) Text to use when the switch is in the checked/"on" state. 
android:textStyle setSwitchTypeface(Typeface) Style (bold, italic, bolditalic) for the text. 
android:thumb setThumbResource(int) Drawable to use as the "thumb" that switches back and forth. 
android:thumbTextPadding setThumbTextPadding(int) Amount of padding on either side of text within the switch thumb. 
android:track setTrackResource(int) Drawable to use as the "track" that the switch thumb slides within. 
android:typeface setSwitchTypeface(Typeface) Typeface (normal, sans, serif, monospace) for the text. 
[Expand]
Inherited XML Attributes
From class android.widget.TextView
From class android.view.View
[Expand]
Inherited Constants
From class android.view.View
[Expand]
Inherited Fields
From class android.view.View
Public Constructors
Switch(Context context)
Construct a new Switch with default styling.
Switch(Context context, AttributeSet attrs)
Construct a new Switch with default styling, overriding specific style attributes as requested.
Switch(Context context, AttributeSet attrs, int defStyle)
Construct a new Switch with a default style determined by the given theme attribute, overriding specific style attributes as requested.
Public Methods
int getCompoundPaddingLeft()
Returns the left padding of the view, plus space for the left Drawable if any.
int getCompoundPaddingRight()
Returns the right padding of the view, plus space for the right Drawable if any.
int getSwitchMinWidth()
Get the minimum width of the switch in pixels.
int getSwitchPadding()
Get the amount of horizontal padding between the switch and the associated text.
CharSequence getTextOff()
Returns the text displayed when the button is not in the checked state.
CharSequence getTextOn()
Returns the text displayed when the button is in the checked state.
Drawable getThumbDrawable()
Get the drawable used for the switch "thumb" - the piece that the user can physically touch and drag along the track.
int getThumbTextPadding()
Get the horizontal padding around the text drawn on the switch itself.
Drawable getTrackDrawable()
Get the drawable used for the track that the switch slides within.
void jumpDrawablesToCurrentState()
Call Drawable.jumpToCurrentState() on all Drawable objects associated with this view.
void onInitializeAccessibilityEvent(AccessibilityEvent event)
Initializes an AccessibilityEvent with information about this View which is the event source.
void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info)
Initializes an AccessibilityNodeInfo with information about this view.
void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height.

void onPopulateAccessibilityEvent(AccessibilityEvent event)
Called from dispatchPopulateAccessibilityEvent(AccessibilityEvent) giving a chance to this View to populate the accessibility event with its text content.
boolean onTouchEvent(MotionEvent ev)
Implement this method to handle touch screen motion events.
void setChecked(boolean checked)

Changes the checked state of this button.

void setSwitchMinWidth(int pixels)
Set the minimum width of the switch in pixels.
void setSwitchPadding(int pixels)
Set the amount of horizontal padding between the switch and the associated text.
void setSwitchTextAppearance(Context context, int resid)
Sets the switch text color, size, style, hint color, and highlight color from the specified TextAppearance resource.
void setSwitchTypeface(Typeface tf, int style)
Sets the typeface and style in which the text should be displayed on the switch, and turns on the fake bold and italic bits in the Paint if the Typeface that you provided does not have all the bits in the style that you specified.
void setSwitchTypeface(Typeface tf)
Sets the typeface in which the text should be displayed on the switch.
void setTextOff(CharSequence textOff)
Sets the text displayed when the button is not in the checked state.
void setTextOn(CharSequence textOn)
Sets the text displayed when the button is in the checked state.
void setThumbDrawable(Drawable thumb)
Set the drawable used for the switch "thumb" - the piece that the user can physically touch and drag along the track.
void setThumbResource(int resId)
Set the drawable used for the switch "thumb" - the piece that the user can physically touch and drag along the track.
void setThumbTextPadding(int pixels)
Set the horizontal padding around the text drawn on the switch itself.
void setTrackDrawable(Drawable track)
Set the drawable used for the track that the switch slides within.
void setTrackResource(int resId)
Set the drawable used for the track that the switch slides within.
Protected Methods
void drawableStateChanged()
This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.
int[] onCreateDrawableState(int extraSpace)
Generate the new Drawable state for this view.
void onDraw(Canvas canvas)
Implement this to do your drawing.
void onLayout(boolean changed, int left, int top, int right, int bottom)
Called from layout when this view should assign a size and position to each of its children.
boolean verifyDrawable(Drawable who)
If your view subclass is displaying its own Drawable objects, it should override this function and return true for any Drawable it is displaying.
[Expand]
Inherited Methods
From class android.widget.CompoundButton
From class android.widget.Button
From class android.widget.TextView
From class android.view.View
From class java.lang.Object
From interface android.graphics.drawable.Drawable.Callback
From interface android.view.KeyEvent.Callback
From interface android.view.ViewTreeObserver.OnPreDrawListener
From interface android.view.accessibility.AccessibilityEventSource
From interface android.widget.Checkable

XML Attributes

android:switchMinWidth

Minimum width for the switch component

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol switchMinWidth.

Related Methods

android:switchPadding

Minimum space between the switch and caption text

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol switchPadding.

Related Methods

android:switchTextAppearance

TextAppearance style for text displayed on the switch thumb.

Must be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name".

This corresponds to the global attribute resource symbol switchTextAppearance.

android:textOff

Text to use when the switch is in the unchecked/"off" state.

Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol textOff.

Related Methods

android:textOn

Text to use when the switch is in the checked/"on" state.

Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol textOn.

Related Methods

android:textStyle

Style (bold, italic, bolditalic) for the text.

Must be one or more (separated by '|') of the following constant values.

ConstantValueDescription
normal0
bold1
italic2

This corresponds to the global attribute resource symbol textStyle.

Related Methods

android:thumb

Drawable to use as the "thumb" that switches back and forth.

Must be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name".

This corresponds to the global attribute resource symbol thumb.

Related Methods

android:thumbTextPadding

Amount of padding on either side of text within the switch thumb.

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol thumbTextPadding.

Related Methods

android:track

Drawable to use as the "track" that the switch thumb slides within.

Must be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name".

This corresponds to the global attribute resource symbol track.

Related Methods

android:typeface

Typeface (normal, sans, serif, monospace) for the text.

Must be one of the following constant values.

ConstantValueDescription
normal0
sans1
serif2
monospace3

This corresponds to the global attribute resource symbol typeface.

Related Methods

Public Constructors

public Switch (Context context)

Added in API level 14

Construct a new Switch with default styling.

Parameters
context The Context that will determine this widget's theming.

public Switch (Context context, AttributeSet attrs)

Added in API level 14

Construct a new Switch with default styling, overriding specific style attributes as requested.

Parameters
context The Context that will determine this widget's theming.
attrs Specification of attributes that should deviate from default styling.

public Switch (Context context, AttributeSet attrs, int defStyle)

Added in API level 14

Construct a new Switch with a default style determined by the given theme attribute, overriding specific style attributes as requested.

Parameters
context The Context that will determine this widget's theming.
attrs Specification of attributes that should deviate from the default styling.
defStyle An attribute ID within the active theme containing a reference to the default style for this widget. e.g. android.R.attr.switchStyle.

Public Methods

public int getCompoundPaddingLeft ()

Added in API level 14

Returns the left padding of the view, plus space for the left Drawable if any.

public int getCompoundPaddingRight ()

Added in API level 14

Returns the right padding of the view, plus space for the right Drawable if any.

public int getSwitchMinWidth ()

Added in API level 16

Get the minimum width of the switch in pixels. The switch's width will be the maximum of this value and its measured width as determined by the switch drawables and text used.

Related XML Attributes
Returns
  • Minimum width of the switch in pixels

public int getSwitchPadding ()

Added in API level 16

Get the amount of horizontal padding between the switch and the associated text.

Related XML Attributes
Returns
  • Amount of padding in pixels

public CharSequence getTextOff ()

Added in API level 14

Returns the text displayed when the button is not in the checked state.

Related XML Attributes

public CharSequence getTextOn ()

Added in API level 14

Returns the text displayed when the button is in the checked state.

Related XML Attributes

public Drawable getThumbDrawable ()

Added in API level 16

Get the drawable used for the switch "thumb" - the piece that the user can physically touch and drag along the track.

Related XML Attributes
Returns
  • Thumb drawable

public int getThumbTextPadding ()

Added in API level 16

Get the horizontal padding around the text drawn on the switch itself.

Related XML Attributes
Returns
  • Horizontal padding for switch thumb text in pixels

public Drawable getTrackDrawable ()

Added in API level 16

Get the drawable used for the track that the switch slides within.

Related XML Attributes
Returns
  • Track drawable

public void jumpDrawablesToCurrentState ()

Added in API level 14

Call Drawable.jumpToCurrentState() on all Drawable objects associated with this view.

public void onInitializeAccessibilityEvent (AccessibilityEvent event)

Added in API level 14

Initializes an AccessibilityEvent with information about this View which is the event source. In other words, the source of an accessibility event is the view whose state change triggered firing the event.

Example: Setting the password property of an event in addition to properties set by the super implementation:

 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
     super.onInitializeAccessibilityEvent(event);
     event.setPassword(true);
 }

If an View.AccessibilityDelegate has been specified via calling setAccessibilityDelegate(AccessibilityDelegate) its onInitializeAccessibilityEvent(View, AccessibilityEvent) is responsible for handling this call.

Note: Always call the super implementation before adding information to the event, in case the default implementation has basic information to add.

Parameters
event The event to initialize.

public void onInitializeAccessibilityNodeInfo (AccessibilityNodeInfo info)

Added in API level 14

Initializes an AccessibilityNodeInfo with information about this view. The base implementation sets:

Subclasses should override this method, call the super implementation, and set additional attributes.

If an View.AccessibilityDelegate has been specified via calling setAccessibilityDelegate(AccessibilityDelegate) its onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo) is responsible for handling this call.

Parameters
info The instance to initialize.

public void onMeasure (int widthMeasureSpec, int heightMeasureSpec)

Added in API level 14

Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overriden by subclasses to provide accurate and efficient measurement of their contents.

CONTRACT: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling the superclass' onMeasure(int, int) is a valid use.

The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should override onMeasure(int, int) to provide better measurements of their content.

If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight() and getSuggestedMinimumWidth()).

Parameters
widthMeasureSpec horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
heightMeasureSpec vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.

public void onPopulateAccessibilityEvent (AccessibilityEvent event)

Added in API level 14

Called from dispatchPopulateAccessibilityEvent(AccessibilityEvent) giving a chance to this View to populate the accessibility event with its text content. While this method is free to modify event attributes other than text content, doing so should normally be performed in onInitializeAccessibilityEvent(AccessibilityEvent).

Example: Adding formatted date string to an accessibility event in addition to the text added by the super implementation:

 public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
     super.onPopulateAccessibilityEvent(event);
     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
         mCurrentDate.getTimeInMillis(), flags);
     event.getText().add(selectedDateUtterance);
 }

If an View.AccessibilityDelegate has been specified via calling setAccessibilityDelegate(AccessibilityDelegate) its onPopulateAccessibilityEvent(View, AccessibilityEvent) is responsible for handling this call.

Note: Always call the super implementation before adding information to the event, in case the default implementation has basic information to add.

Parameters
event The accessibility event which to populate.

public boolean onTouchEvent (MotionEvent ev)

Added in API level 14

Implement this method to handle touch screen motion events.

If this method is used to detect click actions, it is recommended that the actions be performed by implementing and calling performClick(). This will ensure consistent system behavior, including:

  • obeying click sound preferences
  • dispatching OnClickListener calls
  • handling ACTION_CLICK when accessibility features are enabled

Parameters
ev The motion event.
Returns
  • True if the event was handled, false otherwise.

public void setChecked (boolean checked)

Added in API level 14

Changes the checked state of this button.

Parameters
checked true to check the button, false to uncheck it

public void setSwitchMinWidth (int pixels)

Added in API level 16

Set the minimum width of the switch in pixels. The switch's width will be the maximum of this value and its measured width as determined by the switch drawables and text used.

Related XML Attributes
Parameters
pixels Minimum width of the switch in pixels

public void setSwitchPadding (int pixels)

Added in API level 16

Set the amount of horizontal padding between the switch and the associated text.

Related XML Attributes
Parameters
pixels Amount of padding in pixels

public void setSwitchTextAppearance (Context context, int resid)

Added in API level 14

Sets the switch text color, size, style, hint color, and highlight color from the specified TextAppearance resource.

Related XML Attributes

public void setSwitchTypeface (Typeface tf, int style)

Added in API level 14

Sets the typeface and style in which the text should be displayed on the switch, and turns on the fake bold and italic bits in the Paint if the Typeface that you provided does not have all the bits in the style that you specified.

public void setSwitchTypeface (Typeface tf)

Added in API level 14

Sets the typeface in which the text should be displayed on the switch. Note that not all Typeface families actually have bold and italic variants, so you may need to use setSwitchTypeface(Typeface, int) to get the appearance that you actually want.

Related XML Attributes

public void setTextOff (CharSequence textOff)

Added in API level 14

Sets the text displayed when the button is not in the checked state.

Related XML Attributes

public void setTextOn (CharSequence textOn)

Added in API level 14

Sets the text displayed when the button is in the checked state.

Related XML Attributes

public void setThumbDrawable (Drawable thumb)

Added in API level 16

Set the drawable used for the switch "thumb" - the piece that the user can physically touch and drag along the track.

Related XML Attributes
Parameters
thumb Thumb drawable

public void setThumbResource (int resId)

Added in API level 16

Set the drawable used for the switch "thumb" - the piece that the user can physically touch and drag along the track.

Related XML Attributes
Parameters
resId Resource ID of a thumb drawable

public void setThumbTextPadding (int pixels)

Added in API level 16

Set the horizontal padding around the text drawn on the switch itself.

Related XML Attributes
Parameters
pixels Horizontal padding for switch thumb text in pixels

public void setTrackDrawable (Drawable track)

Added in API level 16

Set the drawable used for the track that the switch slides within.

Related XML Attributes
Parameters
track Track drawable

public void setTrackResource (int resId)

Added in API level 16

Set the drawable used for the track that the switch slides within.

Related XML Attributes
Parameters
resId Resource ID of a track drawable

Protected Methods

protected void drawableStateChanged ()

Added in API level 14

This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.

Be sure to call through to the superclass when overriding this function.

protected int[] onCreateDrawableState (int extraSpace)

Added in API level 14

Generate the new Drawable state for this view. This is called by the view system when the cached Drawable state is determined to be invalid. To retrieve the current state, you should use getDrawableState().

Parameters
extraSpace if non-zero, this is the number of extra entries you would like in the returned array in which you can place your own states.
Returns
  • Returns an array holding the current Drawable state of the view.

protected void onDraw (Canvas canvas)

Added in API level 14

Implement this to do your drawing.

Parameters
canvas the canvas on which the background will be drawn

protected void onLayout (boolean changed, int left, int top, int right, int bottom)

Added in API level 14

Called from layout when this view should assign a size and position to each of its children. Derived classes with children should override this method and call layout on each of their children.

Parameters
changed This is a new size or position for this view
left Left position, relative to parent
top Top position, relative to parent
right Right position, relative to parent
bottom Bottom position, relative to parent

protected boolean verifyDrawable (Drawable who)

Added in API level 14

If your view subclass is displaying its own Drawable objects, it should override this function and return true for any Drawable it is displaying. This allows animations for those drawables to be scheduled.

Be sure to call through to the super class when overriding this function.

Parameters
who The Drawable to verify. Return true if it is one you are displaying, else return the result of calling through to the super class.
Returns
  • boolean If true than the Drawable is being displayed in the view; else false and it is not allowed to animate.