SwitchCompat


public class SwitchCompat extends CompoundButton implements EmojiCompatConfigurationView


SwitchCompat is a complete backport of the core Switch widget that brings the visuals and functionality of the toggle widget to older versions of the Android platform. Unlike other widgets in this package, SwitchCompat is not automatically used in layouts that include the <Switch> element. Instead, you need to explicitly use <androidx.appcompat.widget.SwitchCompat> and the matching attributes in your layouts.

The thumb can be tinted with setThumbTintList and setThumbTintMode APIs as well as with the matching XML attributes. The track can be tinted with setTrackTintList and setTrackTintMode APIs as well as with the matching XML attributes.

Supported attributes include:

For more information, see the Toggle Buttons guide.

Summary

Public constructors

Construct a new Switch with default styling.

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

SwitchCompat(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr
)

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

Public methods

void
void
drawableHotspotChanged(float x, float y)
int
int
@Nullable ActionMode.Callback
boolean
@Attribute(value = "androidx.appcompat:showText")
getShowText()

Indicates whether the on/off text should be displayed.

boolean
@Attribute(value = "androidx.appcompat:splitTrack")
getSplitTrack()

Returns whether the track should be split by the thumb.

int
@Attribute(value = "androidx.appcompat:switchMinWidth")
getSwitchMinWidth()

Get the minimum width of the switch in pixels.

int
@Attribute(value = "androidx.appcompat:switchPadding")
getSwitchPadding()

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

CharSequence
@Attribute(value = "android:textOff")
getTextOff()

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

CharSequence
@Attribute(value = "android:textOn")
getTextOn()

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

Drawable
@Attribute(value = "android:thumb")
getThumbDrawable()

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

int
@Attribute(value = "androidx.appcompat:thumbTextPadding")
getThumbTextPadding()

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

@Nullable ColorStateList
@Attribute(value = "androidx.appcompat:thumbTint")
getThumbTintList()
@Nullable PorterDuff.Mode
@Attribute(value = "androidx.appcompat:thumbTintMode")
getThumbTintMode()
Drawable
@Attribute(value = "androidx.appcompat:track")
getTrackDrawable()

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

@Nullable ColorStateList
@Attribute(value = "androidx.appcompat:trackTint")
getTrackTintList()
@Nullable PorterDuff.Mode
@Attribute(value = "androidx.appcompat:trackTintMode")
getTrackTintMode()
boolean
void
void
void
void
onMeasure(int widthMeasureSpec, int heightMeasureSpec)
void
boolean
void
setAllCaps(boolean allCaps)
void
setChecked(boolean checked)
void

See setCustomSelectionActionModeCallback

void
setEmojiCompatEnabled(boolean enabled)

Configure emoji fallback behavior using EmojiCompat.

void
setFilters(@NonNull InputFilter[] filters)
void
setShowText(boolean showText)

Sets whether the on/off text should be displayed.

void
setSplitTrack(boolean splitTrack)

Specifies whether the track should be split by the thumb.

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

Sets the typeface in which the text should be displayed on the switch.

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

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

void

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

void

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

Applies a tint to the thumb drawable.

void

Specifies the blending mode used to apply the tint specified by setThumbTintList} to the thumb drawable.

void

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.

void

Applies a tint to the track drawable.

void

Specifies the blending mode used to apply the tint specified by setTrackTintList to the track drawable.

void

Protected methods

void
final @FloatRange(from = 0.0, to = 1.0) float
int[]
onCreateDrawableState(int extraSpace)
void
onDraw(Canvas canvas)
void
onLayout(boolean changed, int left, int top, int right, int bottom)
final void
setEnforceSwitchWidth(boolean enforceSwitchWidth)

Sets true to enforce the switch width being at least twice of the thumb width.

boolean

Inherited Constants

From android.widget.TextView
static final int
static final int
static final int
From android.view.View
static final int
static final int
static final int
static final int
static final int
static final int
static final Property<ViewFloat>
static final int
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE = "creditCardExpirationDate"
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay"
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH = "creditCardExpirationMonth"
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR = "creditCardExpirationYear"
static final String
static final String
AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode"
static final String
static final String
static final String
static final String
static final String
static final String
static final String
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int
static final int
static final int
static final int
static final int
static final int
static final int[]
static final int[]
static final int[]
static final int[]
static final int
static final int
static final int
static final int
static final int
static final int
static final int
GONE = 8
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
KEEP_SCREEN_ON = 67108864
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
NO_ID = -1
static final int
static final int
static final int
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int[]
static final int[]
static final int
static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final String
VIEW_LOG_TAG = "View"
static final int
static final int[]
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>

Inherited methods

From android.widget.Button
PointerIcon
onResolvePointerIcon(MotionEvent event, int pointerIndex)
From android.widget.CompoundButton
From android.widget.TextView
void
addExtraDataToAccessibilityNodeInfo(
    AccessibilityNodeInfo info,
    String extraDataKey,
    Bundle arguments
)
void
final void
void
boolean
bringPointIntoView(int offset)
void
void
int
void
int
int
void
debug(int depth)
boolean
void
boolean
void
findViewsWithText(
    ArrayList<View> outViews,
    CharSequence searched,
    int flags
)
final int
int
int
int
int[]
int
String[]
int
int
int
int
BlendMode
ColorStateList
PorterDuff.Mode
Drawable[]
Drawable[]
int
int
int
int
final int
final int
ActionMode.Callback
boolean
MovementMethod
Editable
TextUtils.TruncateAt
CharSequence
int
int
InputFilter[]
int
void
int
int
String
String
boolean
int
int
Highlights
CharSequence
final ColorStateList
int
int
CharSequence
LocaleList
int
boolean
Bundle
getInputExtras(boolean create)
int
int
final KeyListener
int
final Layout
float
int
float
int
getLineBounds(int line, Rect bounds)
int
int
int
int
float
float
final ColorStateList
final boolean
int
int
int
int
int
int
int
int
int
final MovementMethod
int
getOffsetForPosition(float x, float y)
TextPaint
int
String
float
int
int
int[]
int
int
int
float
float
float
final boolean
CharSequence
TextClassifier
final ColorStateList
Drawable
TextDirectionHeuristic
Locale
LocaleList
PrecomputedText.Params
float
Drawable
Drawable
Drawable
float
int
int
int
int
int
int
int
int
final TransformationMethod
Typeface
URLSpan[]
boolean
boolean
void
boolean
boolean
boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
int
boolean
void
void
boolean
void
void
void
void
InputConnection
void
onCreateViewTranslationRequest(
    int[] supportedFormats,
    Consumer<ViewTranslationRequest> requestsCollector
)
boolean
void
onEditorAction(int actionCode)
void
void
onFocusChanged(
    boolean focused,
    int direction,
    Rect previouslyFocusedRect
)
boolean
boolean
onKeyDown(int keyCode, KeyEvent event)
boolean
onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
boolean
onKeyPreIme(int keyCode, KeyEvent event)
boolean
onKeyShortcut(int keyCode, KeyEvent event)
boolean
onKeyUp(int keyCode, KeyEvent event)
boolean
boolean
ContentInfo
void
onRtlPropertiesChanged(int layoutDirection)
void
onScreenStateChanged(int screenState)
void
onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert)
void
onSelectionChanged(int selStart, int selEnd)
void
onTextChanged(
    CharSequence text,
    int start,
    int lengthBefore,
    int lengthAfter
)
boolean
boolean
void
onVisibilityAggregated(boolean isVisible)
void
onVisibilityChanged(View changedView, int visibility)
void
onWindowFocusChanged(boolean hasWindowFocus)
boolean
void
void
final void
setAutoLinkMask(int mask)
void
setAutoSizeTextTypeUniformWithConfiguration(
    int autoSizeMinTextSize,
    int autoSizeMaxTextSize,
    int autoSizeStepGranularity,
    int unit
)
void
setAutoSizeTextTypeUniformWithPresetSizes(int[] presetSizes, int unit)
void
setAutoSizeTextTypeWithDefaults(int autoSizeTextType)
void
setBreakStrategy(int breakStrategy)
void
void
void
void
void
setCompoundDrawables(
    Drawable left,
    Drawable top,
    Drawable right,
    Drawable bottom
)
void
setCompoundDrawablesRelative(
    Drawable start,
    Drawable top,
    Drawable end,
    Drawable bottom
)
void
setCompoundDrawablesRelativeWithIntrinsicBounds(
    int start,
    int top,
    int end,
    int bottom
)
void
setCompoundDrawablesWithIntrinsicBounds(
    int left,
    int top,
    int right,
    int bottom
)
void
setCursorVisible(boolean visible)
void
final void
void
setElegantTextHeight(boolean elegant)
void
void
setEms(int ems)
void
setEnabled(boolean enabled)
void
void
void
setFallbackLineSpacing(boolean enabled)
void
setFirstBaselineToTopHeight(int firstBaselineToTopHeight)
void
void
void
setFontFeatureSettings(String fontFeatureSettings)
boolean
setFontVariationSettings(String fontVariationSettings)
boolean
setFrame(int l, int t, int r, int b)
void
setFreezesText(boolean freezesText)
void
setGravity(int gravity)
void
setHeight(int pixels)
void
setHighlightColor(int color)
void
final void
final void
setHintTextColor(int color)
void
setHorizontallyScrolling(boolean whether)
void
setHyphenationFrequency(int hyphenationFrequency)
void
setImeActionLabel(CharSequence label, int actionId)
void
void
setImeOptions(int imeOptions)
void
setIncludeFontPadding(boolean includepad)
void
setInputExtras(int xmlResId)
void
setInputType(int type)
void
setJustificationMode(int justificationMode)
void
void
setLastBaselineToBottomHeight(int lastBaselineToBottomHeight)
void
setLetterSpacing(float letterSpacing)
void
setLineBreakStyle(int lineBreakStyle)
void
setLineBreakWordStyle(int lineBreakWordStyle)
void
setLineHeight(int lineHeight)
void
setLineSpacing(float add, float mult)
void
setLines(int lines)
final void
setLinkTextColor(int color)
final void
setLinksClickable(boolean whether)
void
setMarqueeRepeatLimit(int marqueeLimit)
void
setMaxEms(int maxEms)
void
setMaxHeight(int maxPixels)
void
setMaxLines(int maxLines)
void
setMaxWidth(int maxPixels)
void
setMinEms(int minEms)
void
setMinHeight(int minPixels)
void
setMinLines(int minLines)
void
setMinWidth(int minPixels)
final void
void
void
setPadding(int left, int top, int right, int bottom)
void
setPaddingRelative(int start, int top, int end, int bottom)
void
setPaintFlags(int flags)
void
void
setRawInputType(int type)
void
void
void
void
setSelectAllOnFocus(boolean selectAllOnFocus)
void
setSelected(boolean selected)
void
setShadowLayer(float radius, float dx, float dy, int color)
final void
void
final void
final void
void
setTextAppearance(int resId)
void
void
setTextColor(int color)
void
setTextCursorDrawable(Drawable textCursorDrawable)
void
setTextIsSelectable(boolean selectable)
final void
void
void
void
void
setTextScaleX(float size)
void
setTextSelectHandle(Drawable textSelectHandle)
void
setTextSelectHandleLeft(Drawable textSelectHandleLeft)
void
setTextSelectHandleRight(Drawable textSelectHandleRight)
void
setTextSize(float size)
final void
void
setTypeface(Typeface tf, int style)
void
setWidth(int pixels)
boolean
From android.view.View
void
void
addFocusables(ArrayList<View> views, int direction)
void
void
void
void
void
ViewPropertyAnimator
void
boolean
void
void

This method is deprecated.

void
boolean
boolean
boolean
boolean
boolean
canScrollHorizontally(int direction)
boolean
canScrollVertically(int direction)
final void
final void
boolean
void
void
void
static int
combineMeasuredStates(int curState, int newState)
int
int
WindowInsets
int
AccessibilityNodeInfo
void
void

This method is deprecated.

WindowInsets
boolean
void
void
dispatchCreateViewTranslationRequest(
    Map<AutofillId, long[]> viewIds,
    int[] supportedFormats,
    TranslationCapability capability,
    List<ViewTranslationRequest> requests
)
void
boolean
void
void
dispatchDrawableHotspotChanged(float x, float y)
void
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
dispatchNestedFling(float velocityX, float velocityY, boolean consumed)
boolean
dispatchNestedPreFling(float velocityX, float velocityY)
boolean
dispatchNestedPrePerformAccessibilityAction(
    int action,
    Bundle arguments
)
boolean
dispatchNestedPreScroll(
    int dx,
    int dy,
    int[] consumed,
    int[] offsetInWindow
)
boolean
dispatchNestedScroll(
    int dxConsumed,
    int dyConsumed,
    int dxUnconsumed,
    int dyUnconsumed,
    int[] offsetInWindow
)
void
dispatchPointerCaptureChanged(boolean hasCapture)
boolean
void
void
void
void
void
dispatchScrollCaptureSearch(
    Rect localVisibleRect,
    Point windowOffset,
    Consumer<ScrollCaptureTarget> targets
)
void
dispatchSetActivated(boolean activated)
void
dispatchSetPressed(boolean pressed)
void
dispatchSetSelected(boolean selected)
void
void

This method is deprecated.

boolean
boolean
boolean
dispatchUnhandledMove(View focused, int direction)
void
dispatchVisibilityChanged(View changedView, int visibility)
void
dispatchWindowFocusChanged(boolean hasFocus)
void
void
WindowInsets
WindowInsetsAnimation.Bounds
void

This method is deprecated.

void
View
final OnBackInvokedDispatcher
final T
<T extends View> findViewById(int id)
final T
<T extends View> findViewWithTag(Object tag)
boolean

This method is deprecated.

View
focusSearch(int direction)
void
forceHasOverlappingRendering(boolean hasOverlappingRendering)
void
boolean
void
generateDisplayHash(
    String hashAlgorithm,
    Rect bounds,
    Executor executor,
    DisplayHashResultCallback callback
)
static int
View.AccessibilityDelegate
int
AccessibilityNodeProvider
CharSequence
int
int
String
String
float
Animation
Matrix
IBinder
int[]
Map<IntegerInteger>
final AutofillId
Drawable
BlendMode
ColorStateList
PorterDuff.Mode
final int
float
float
Rect
boolean
final boolean
final ContentCaptureSession
CharSequence
final Context
ContextMenu.ContextMenuInfo
final boolean
static int
getDefaultSize(int size, int measureSpec)
Display
final int[]
Bitmap

This method is deprecated.

int

This method is deprecated.

int

This method is deprecated.

void
long
float
int
boolean
boolean
int
ArrayList<View>
getFocusables(int direction)
Drawable
int
BlendMode
ColorStateList
PorterDuff.Mode
boolean
getGlobalVisibleRect(Rect r, Point globalOffset)
Handler
float
float
float
float
Runnable
final boolean
final int
void
getHitRect(Rect outRect)
int
int
Drawable
Drawable
int
int
int
int
boolean
KeyEvent.DispatcherState
int
int
int
ViewGroup.LayoutParams
final int
final boolean
void
getLocationInSurface(int[] location)
void
getLocationInWindow(int[] outLocation)
void
getLocationOnScreen(int[] outLocation)
Matrix
final int
final int
final int
final int
final int
int
int
int
int
int
int
int
int
View.OnFocusChangeListener
int
ViewOutlineProvider
int
int
ViewOverlay
int
int
int
int
int
int
final ViewParent
ViewParent
float
float
PointerIcon
final List<Rect>
String[]
Resources
final boolean
final int
AttachedSurfaceControl
View
WindowInsets
float
float
float
float
float
int
int
int
int
int
int
final int
final int
int
int
final CharSequence
StateListAnimator
int
int
List<Rect>
int

This method is deprecated.

Object
int
int
CharSequence
final int
float
TouchDelegate
ArrayList<View>
float
String
float
float
float
long
int
int
Drawable
Drawable
int
ViewTranslationResponse
ViewTreeObserver
int
final int
int
WindowId
WindowInsetsController
int

This method is deprecated.

IBinder
int
void
float
float
float
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
static View
inflate(Context context, int resource, ViewGroup root)
void

This method is deprecated.

void
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean

This method is deprecated.

boolean
boolean
final boolean
final boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final boolean
final boolean
boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
View
keyboardNavigationClusterSearch(View currentCluster, int direction)
void
layout(int l, int t, int r, int b)
final void
measure(int widthMeasureSpec, int heightMeasureSpec)
static int[]
mergeDrawableStates(int[] baseState, int[] additionalState)
void
offsetLeftAndRight(int offset)
void
offsetTopAndBottom(int offset)
void
void
WindowInsets
void
boolean
void
onCreateVirtualViewTranslationRequests(
    long[] virtualIds,
    int[] supportedFormats,
    Consumer<ViewTranslationRequest> requestsCollector
)
void
void
onDisplayHint(int hint)
void
final void
boolean
void
void
void
onHoverChanged(boolean hovered)
boolean
boolean
onKeyLongPress(int keyCode, KeyEvent event)
void
onOverScrolled(
    int scrollX,
    int scrollY,
    boolean clampedX,
    boolean clampedY
)
void
onPointerCaptureChange(boolean hasCapture)
void
onProvideAutofillStructure(ViewStructure structure, int flags)
void
void
void
void
void
onScrollCaptureSearch(
    Rect localVisibleRect,
    Point windowOffset,
    Consumer<ScrollCaptureTarget> targets
)
boolean
onSetAlpha(int alpha)
void
onSizeChanged(int w, int h, int oldw, int oldh)
void
void
void
void

This method is deprecated.

void
onWindowVisibilityChanged(int visibility)
boolean
overScrollBy(
    int deltaX,
    int deltaY,
    int scrollX,
    int scrollY,
    int scrollRangeX,
    int scrollRangeY,
    int maxOverScrollX,
    int maxOverScrollY,
    boolean isTouchEvent
)
boolean
performAccessibilityAction(int action, Bundle arguments)
boolean
performContextClick(float x, float y)
boolean
performHapticFeedback(int feedbackConstant)
ContentInfo
void
playSoundEffect(int soundConstant)
boolean
post(Runnable action)
boolean
postDelayed(Runnable action, long delayMillis)
void
void
postInvalidateDelayed(long delayMilliseconds)
void
void
void
postOnAnimationDelayed(Runnable action, long delayMillis)
void
void
boolean
void
void
void
void
void

This method is deprecated.

final boolean
final boolean
void
void
boolean
final void
final T
<T extends View> requireViewById(int id)
void
static int
resolveSize(int size, int measureSpec)
static int
resolveSizeAndState(int size, int measureSpec, int childMeasuredState)
boolean
void
final void
saveAttributeDataForStyleable(
    Context context,
    int[] styleable,
    AttributeSet attrs,
    TypedArray t,
    int defStyleAttr,
    int defStyleRes
)
void
void
scheduleDrawable(Drawable who, Runnable what, long when)
void
scrollBy(int x, int y)
void
scrollTo(int x, int y)
void
sendAccessibilityEvent(int eventType)
void
setAccessibilityDataSensitive(int accessibilityDataSensitive)
void
void
setAccessibilityHeading(boolean isHeading)
void
void
setAccessibilityPaneTitle(CharSequence accessibilityPaneTitle)
void
void
void
setActivated(boolean activated)
void
setAllowClickWhenDisabled(boolean clickableWhenDisabled)
void
void
void
setAlpha(float alpha)
void
void
void
setAutoHandwritingEnabled(boolean enabled)
void
setAutofillHints(String[] autofillHints)
void
void
setBackground(Drawable background)
void
setBackgroundColor(int color)
void

This method is deprecated.

void
void
void
void
final void
setBottom(int bottom)
void
setCameraDistance(float distance)
void
setClickable(boolean clickable)
void
setClipBounds(Rect clipBounds)
void
setClipToOutline(boolean clipToOutline)
void
void
setContentDescription(CharSequence contentDescription)
void
setContextClickable(boolean contextClickable)
void
setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled)
void

This method is deprecated.

void
setDrawingCacheEnabled(boolean enabled)

This method is deprecated.

void

This method is deprecated.

void
void
setElevation(float elevation)
void
setFadingEdgeLength(int length)
void
void
setFitsSystemWindows(boolean fitSystemWindows)
void
setFocusable(boolean focusable)
void
setFocusableInTouchMode(boolean focusableInTouchMode)
void
setFocusedByDefault(boolean isFocusedByDefault)
void
setForceDarkAllowed(boolean allow)
void
setForeground(Drawable foreground)
void
setForegroundGravity(int gravity)
void
void
void
void
setHandwritingBoundsOffsets(
    float offsetLeft,
    float offsetTop,
    float offsetRight,
    float offsetBottom
)
void
void
setHapticFeedbackEnabled(boolean hapticFeedbackEnabled)
void
setHasTransientState(boolean hasTransientState)
void
setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled)
void
setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled)
void
void
void
setHovered(boolean hovered)
void
setId(int id)
void
void
void
void
setIsCredential(boolean isCredential)
void
setIsHandwritingDelegate(boolean isHandwritingDelegate)
void
setKeepScreenOn(boolean keepScreenOn)
void
setKeyboardNavigationCluster(boolean isCluster)
void
setLabelFor(int id)
void
void
setLayerType(int layerType, Paint paint)
void
setLayoutDirection(int layoutDirection)
void
final void
setLeft(int left)
final void
setLeftTopRightBottom(int left, int top, int right, int bottom)
void
setLongClickable(boolean longClickable)
final void
setMeasuredDimension(int measuredWidth, int measuredHeight)
void
setMinimumHeight(int minHeight)
void
setMinimumWidth(int minWidth)
void
setNestedScrollingEnabled(boolean enabled)
void
setNextClusterForwardId(int nextClusterForwardId)
void
setNextFocusDownId(int nextFocusDownId)
void
setNextFocusForwardId(int nextFocusForwardId)
void
setNextFocusLeftId(int nextFocusLeftId)
void
setNextFocusRightId(int nextFocusRightId)
void
setNextFocusUpId(int nextFocusUpId)
void
void
void
void
void
void
void
void
void
void
void
void
setOnReceiveContentListener(
    String[] mimeTypes,
    OnReceiveContentListener listener
)
void
void

This method is deprecated.

void
void
void
void
void
setOverScrollMode(int overScrollMode)
void
setPivotX(float pivotX)
void
setPivotY(float pivotY)
void
final void
setPreferKeepClear(boolean preferKeepClear)
final void
void
setPressed(boolean pressed)
void
final void
setRevealOnFocusHint(boolean revealOnFocus)
final void
setRight(int right)
void
setRotation(float rotation)
void
setRotationX(float rotationX)
void
setRotationY(float rotationY)
void
setSaveEnabled(boolean enabled)
void
setSaveFromParentEnabled(boolean enabled)
void
setScaleX(float scaleX)
void
setScaleY(float scaleY)
void
setScreenReaderFocusable(boolean screenReaderFocusable)
void
setScrollBarDefaultDelayBeforeFade(
    int scrollBarDefaultDelayBeforeFade
)
void
setScrollBarFadeDuration(int scrollBarFadeDuration)
void
setScrollBarSize(int scrollBarSize)
void
setScrollBarStyle(int style)
final void
void
void
setScrollContainer(boolean isScrollContainer)
void
setScrollIndicators(int indicators)
void
setScrollX(int value)
void
setScrollY(int value)
void
setScrollbarFadingEnabled(boolean fadeScrollbars)
void
setSoundEffectsEnabled(boolean soundEffectsEnabled)
void
void
void
setSystemUiVisibility(int visibility)

This method is deprecated.

void
void
setTextAlignment(int textAlignment)
void
setTextDirection(int textDirection)
void
final void
setTop(int top)
void
void
setTransitionAlpha(float alpha)
final void
setTransitionName(String transitionName)
void
setTransitionVisibility(int visibility)
void
setTranslationX(float translationX)
void
setTranslationY(float translationY)
void
setTranslationZ(float translationZ)
void
setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled)
void
setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled)
void
void
void
void
void
setVisibility(int visibility)
void
setWillNotCacheDrawing(boolean willNotCacheDrawing)

This method is deprecated.

void
setWillNotDraw(boolean willNotDraw)
void
void
setX(float x)
void
setY(float y)
void
setZ(float z)
ActionMode
void
final boolean
startDrag(
    ClipData data,
    View.DragShadowBuilder shadowBuilder,
    Object myLocalState,
    int flags
)

This method is deprecated.

final boolean
startDragAndDrop(
    ClipData data,
    View.DragShadowBuilder shadowBuilder,
    Object myLocalState,
    int flags
)
boolean
void
String
void
void
void
final void
boolean

This method is deprecated.

boolean

Public constructors

SwitchCompat

Added in 1.1.0
public SwitchCompat(@NonNull Context context)

Construct a new Switch with default styling.

Parameters
@NonNull Context context

The Context that will determine this widget's theming.

SwitchCompat

Added in 1.1.0
public SwitchCompat(@NonNull Context context, @Nullable AttributeSet attrs)

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

Parameters
@NonNull Context context

The Context that will determine this widget's theming.

@Nullable AttributeSet attrs

Specification of attributes that should deviate from default styling.

SwitchCompat

Added in 1.1.0
public SwitchCompat(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr
)

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

Parameters
@NonNull Context context

The Context that will determine this widget's theming.

@Nullable AttributeSet attrs

Specification of attributes that should deviate from the default styling.

int defStyleAttr

An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.

Public methods

draw

public void draw(@NonNull Canvas c)

drawableHotspotChanged

public void drawableHotspotChanged(float x, float y)

getCompoundPaddingLeft

public int getCompoundPaddingLeft()

getCompoundPaddingRight

public int getCompoundPaddingRight()

getCustomSelectionActionModeCallback

public @Nullable ActionMode.Callback getCustomSelectionActionModeCallback()

getShowText

Added in 1.1.0
@Attribute(value = "androidx.appcompat:showText")
public boolean getShowText()

Indicates whether the on/off text should be displayed.

Returns
boolean

true if the on/off text should be displayed, otherwise false

See also
showText

getSplitTrack

Added in 1.1.0
@Attribute(value = "androidx.appcompat:splitTrack")
public boolean getSplitTrack()

Returns whether the track should be split by the thumb.

See also
splitTrack

getSwitchMinWidth

Added in 1.1.0
@Attribute(value = "androidx.appcompat:switchMinWidth")
public int getSwitchMinWidth()

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.

Returns
int

Minimum width of the switch in pixels

See also
switchMinWidth

getSwitchPadding

Added in 1.1.0
@Attribute(value = "androidx.appcompat:switchPadding")
public int getSwitchPadding()

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

Returns
int

Amount of padding in pixels

See also
switchPadding

getTextOff

Added in 1.1.0
@Attribute(value = "android:textOff")
public CharSequence getTextOff()

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

See also
textOff

getTextOn

Added in 1.1.0
@Attribute(value = "android:textOn")
public CharSequence getTextOn()

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

See also
textOn

getThumbDrawable

Added in 1.1.0
@Attribute(value = "android:thumb")
public Drawable getThumbDrawable()

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

Returns
Drawable

Thumb drawable

See also
thumb

getThumbTextPadding

Added in 1.1.0
@Attribute(value = "androidx.appcompat:thumbTextPadding")
public int getThumbTextPadding()

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

Returns
int

Horizontal padding for switch thumb text in pixels

See also
thumbTextPadding

getThumbTintList

Added in 1.1.0
@Attribute(value = "androidx.appcompat:thumbTint")
public @Nullable ColorStateList getThumbTintList()
Returns
@Nullable ColorStateList

the tint applied to the thumb drawable

getThumbTintMode

Added in 1.1.0
@Attribute(value = "androidx.appcompat:thumbTintMode")
public @Nullable PorterDuff.Mode getThumbTintMode()
Returns
@Nullable PorterDuff.Mode

the blending mode used to apply the tint to the thumb drawable

getTrackDrawable

Added in 1.1.0
@Attribute(value = "androidx.appcompat:track")
public Drawable getTrackDrawable()

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

Returns
Drawable

Track drawable

See also
track

getTrackTintList

Added in 1.1.0
@Attribute(value = "androidx.appcompat:trackTint")
public @Nullable ColorStateList getTrackTintList()
Returns
@Nullable ColorStateList

the tint applied to the track drawable

getTrackTintMode

Added in 1.1.0
@Attribute(value = "androidx.appcompat:trackTintMode")
public @Nullable PorterDuff.Mode getTrackTintMode()
Returns
@Nullable PorterDuff.Mode

the blending mode used to apply the tint to the track drawable

isEmojiCompatEnabled

Added in 1.7.0
public boolean isEmojiCompatEnabled()
Returns
boolean

the current enabled state, set via setEmojiCompatEnabled

jumpDrawablesToCurrentState

public void jumpDrawablesToCurrentState()

onInitializeAccessibilityEvent

public void onInitializeAccessibilityEvent(AccessibilityEvent event)

onInitializeAccessibilityNodeInfo

public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info)

onMeasure

Added in 1.1.0
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

onPopulateAccessibilityEvent

public void onPopulateAccessibilityEvent(AccessibilityEvent event)

onTouchEvent

public boolean onTouchEvent(MotionEvent ev)

setAllCaps

public void setAllCaps(boolean allCaps)

setChecked

public void setChecked(boolean checked)

setCustomSelectionActionModeCallback

public void setCustomSelectionActionModeCallback(
    @Nullable ActionMode.Callback actionModeCallback
)

See setCustomSelectionActionModeCallback

setEmojiCompatEnabled

Added in 1.7.0
public void setEmojiCompatEnabled(boolean enabled)

Configure emoji fallback behavior using EmojiCompat. When enabled, this View will attempt to use EmojiCompat to enabled missing emojis. When disabled, this View will not display missing emojis using EmojiCompat. EmojiCompat must be correctly configured on a device for this to have an effect, which will happen by default if a correct downloadable fonts provider is installed on the device. If you manually configure EmojiCompat by calling EmojiCompat init after this View is constructed, you may call this method again to enable EmojiCompat on this text view. For more information about EmojiCompat configuration see the emoji2 module.

Parameters
boolean enabled

if true, display missing emoji using EmojiCompat, otherwise display missing emoji using a fallback glyph "□" (known as tofu)

setFilters

public void setFilters(@NonNull InputFilter[] filters)

setShowText

Added in 1.1.0
public void setShowText(boolean showText)

Sets whether the on/off text should be displayed.

Parameters
boolean showText

true to display on/off text

See also
showText

setSplitTrack

Added in 1.1.0
public void setSplitTrack(boolean splitTrack)

Specifies whether the track should be split by the thumb. When true, the thumb's optical bounds will be clipped out of the track drawable, then the thumb will be drawn into the resulting gap.

Parameters
boolean splitTrack

Whether the track should be split by the thumb

See also
splitTrack

setSwitchMinWidth

Added in 1.1.0
public void setSwitchMinWidth(int pixels)

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.

Parameters
int pixels

Minimum width of the switch in pixels

See also
switchMinWidth

setSwitchPadding

Added in 1.1.0
public void setSwitchPadding(int pixels)

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

Parameters
int pixels

Amount of padding in pixels

See also
switchPadding

setSwitchTextAppearance

Added in 1.1.0
public void setSwitchTextAppearance(Context context, int resid)

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

setSwitchTypeface

Added in 1.1.0
public void setSwitchTypeface(Typeface typeface)

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 to get the appearance that you actually want.

setSwitchTypeface

Added in 1.1.0
public 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.

setTextOff

Added in 1.1.0
public void setTextOff(CharSequence textOff)

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

See also
textOff

setTextOn

Added in 1.1.0
public void setTextOn(CharSequence textOn)

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

See also
textOn

setThumbDrawable

Added in 1.1.0
public 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.

Parameters
Drawable thumb

Thumb drawable

See also
thumb

setThumbResource

Added in 1.1.0
public 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.

Parameters
int resId

Resource ID of a thumb drawable

See also
thumb

setThumbTextPadding

Added in 1.1.0
public void setThumbTextPadding(int pixels)

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

Parameters
int pixels

Horizontal padding for switch thumb text in pixels

See also
thumbTextPadding

setThumbTintList

Added in 1.1.0
public void setThumbTintList(@Nullable ColorStateList tint)

Applies a tint to the thumb drawable. Does not modify the current tint mode, which is SRC_IN by default.

Subsequent calls to setThumbDrawable will automatically mutate the drawable and apply the specified tint and tint mode using setTintList.

Parameters
@Nullable ColorStateList tint

the tint to apply, may be null to clear tint

setThumbTintMode

Added in 1.1.0
public void setThumbTintMode(@Nullable PorterDuff.Mode tintMode)

Specifies the blending mode used to apply the tint specified by setThumbTintList} to the thumb drawable. The default mode is SRC_IN.

Parameters
@Nullable PorterDuff.Mode tintMode

the blending mode used to apply the tint, may be null to clear tint

setTrackDrawable

Added in 1.1.0
public void setTrackDrawable(Drawable track)

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

Parameters
Drawable track

Track drawable

See also
track

setTrackResource

Added in 1.1.0
public void setTrackResource(int resId)

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

Parameters
int resId

Resource ID of a track drawable

See also
track

setTrackTintList

Added in 1.1.0
public void setTrackTintList(@Nullable ColorStateList tint)

Applies a tint to the track drawable. Does not modify the current tint mode, which is SRC_IN by default.

Subsequent calls to setTrackDrawable will automatically mutate the drawable and apply the specified tint and tint mode using setTintList.

Parameters
@Nullable ColorStateList tint

the tint to apply, may be null to clear tint

setTrackTintMode

Added in 1.1.0
public void setTrackTintMode(@Nullable PorterDuff.Mode tintMode)

Specifies the blending mode used to apply the tint specified by setTrackTintList to the track drawable. The default mode is SRC_IN.

Parameters
@Nullable PorterDuff.Mode tintMode

the blending mode used to apply the tint, may be null to clear tint

toggle

public void toggle()

Protected methods

drawableStateChanged

protected void drawableStateChanged()

getThumbPosition

Added in 1.5.0
protected final @FloatRange(from = 0.0, to = 1.0) float getThumbPosition()
Returns
@FloatRange(from = 0.0, to = 1.0) float

the current thumb position as a decimal value between 0 (off) and 1 (on).

onCreateDrawableState

protected int[] onCreateDrawableState(int extraSpace)

onDraw

protected void onDraw(Canvas canvas)

onLayout

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

setEnforceSwitchWidth

Added in 1.5.0
protected final void setEnforceSwitchWidth(boolean enforceSwitchWidth)

Sets true to enforce the switch width being at least twice of the thumb width. Otherwise the switch width will be the value set by setSwitchMinWidth. The default value is true.

verifyDrawable

protected boolean verifyDrawable(@NonNull Drawable who)