Class Switch
- All Implemented Interfaces:
Animation, Editable, ActionSource, StyleListener, ReleasableComponent
The on/off switch is a checkbox of sort (although it derives container) that represents its state as a switch When using the Android native theme, this implementation follows the Material Design Switch guidelines: https://material.io/guidelines/components/selection-controls.html#selection-controls-radio-button
Customizing Look and Feel
You can customize the look and feel of a switch using styles, either directly in the theme.res file or in CSS. This component consists of two elements: the "thumb" the "track". The "thumb" is the circular handle that can be toggled/dragged between an on and off position. The "track" is the background track along which the "thumb" appears to slide when it is dragged/toggled.
The thumb will be rendered using Switch's Style#getFgColor(). It will use the
selected style, when in the "on" position, the unselected style when in the "off" position,
and the disabled style, when #isEnabled() is false.
The track will be rendered using the Switch's Style#getBgColor(). It will
use the selected style, when in the "on" position, and the unselected style when in the "off"
position.
You can also adjust the thumb and track sizes using the following theme constants:
switchThumbScaleYA floating point value used to scale the thumb's diameter, relative to the font size. In the android native theme, this value is set to 1.5. On iOS, it is set to 1.4. switchTrackScaleYA floating point value used to scale the track's height, relative the the font size. In the android native theme, this value is set to 0.9. On iOS, it is set to 1.5 switchTrackScaleXA floating point value used to scale the track's width relative to the font size. In the Android native theme, this value is set to 3.0. On iOS it is 2.5 switchTrackOffOutlineWidthMMA floating point value used to set the stroke/outline thickness of the track when the switch is in the "off" position. In the Android native theme, this is set to 0. On iOS it is 0.25 switchTrackOnOutlineWidthMMA floating point value used to set the stroke/outline thickness of the track when the switch is in the "on" position. In both the Android native theme and the iOS native theme, this is set to 0. switchTrackOffOutlineColorThe color used to stroke the outline for the track when the switch is in the "off" position, expressed as a base-16 int. In the iOS native theme, this is set to "cccccc". switchTrackOnOutlineColorThe color used to stroke the outline for the track when the switch is in the "on" position, expressed as a base-16 int. This is currently not used in either Android or iOS. switchThumbInsetMMAn inset to use when rendering the thumb that will cause it to be inset from the edge of the track. In the iOS native theme, this is 0.25
IMPORTANT: when changing the UIID of the switch the constants
above implicitly change to match the new UIID with the same convetion. So if
your UIID is MySwitch then a theme constant will become:
myswitchTrackScaleY. Notice that the whole UIID is lower cased...
CSS used in the Android native theme:
`#Constants {
...
switchThumbPaddingInt: 2;
switchThumbScaleY: "1.5";
switchTrackScaleY: "0.9";
switchTrackScaleX: "3";
switchTrackOffOutlineWidthMM: "0";
switchTrackOnOutlineWidthMM: "0";
switchTrackOffOutlineColor: "cccccc";
switchThumbInsetMM: "0";`
Switch {
color: rgb(237, 237, 237);
background-color: rgb(159, 158, 158);
}
Switch.selected {
color: rgb(34,44,50);
background-color: rgb(117, 126, 132);
}
}
CSS used in the iOS native theme:
`#Constants {
...
switchThumbPaddingInt: 2;
switchThumbScaleY: "1.4";
switchTrackScaleY: "1.5";
switchTrackScaleX: "2.5";
switchTrackOffOutlineWidthMM: "0.25";
switchTrackOnOutlineWidthMM: "0";
switchTrackOffOutlineColor: "cccccc";
switchThumbInsetMM: "0.25";`
Switch {
color: white;
background-color: white;
}
Switch.selected {
color: white;
background-color: rgb(61, 216, 76);
}
}
Using Custom Thumb and Track Images
You can optionally provide custom images for use as the track or thumb via the following theme constants
-
switchThumbOnImage
-
switchThumbOffImage
-
switchThumbDisabledImage
-
switchOnTrackImage
-
switchOffTrackImage
-
switchDisabledTrackImage
-
Field Summary
Fields inherited from class Component
BASELINE, BOTTOM, BRB_CENTER_OFFSET, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_OTHER, CENTER, CROSSHAIR_CURSOR, DEFAULT_CURSOR, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_POSSIBLE_DRAG_Y, E_RESIZE_CURSOR, HAND_CURSOR, LEFT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NW_RESIZE_CURSOR, RIGHT, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, TOP, W_RESIZE_CURSOR, WAIT_CURSOR -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidAdds a listener to the switch which will cause an event to dispatch on clickvoidAdds a listener to the switch which will cause an event on changeprotected DimensionCalculates the preferred size based on component content.protected voidInvoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy.Some components may optionally generate a state which can then be restored using setCompnentState().protected intgetDragRegionStatus(int x, int y) Indicates if the section within the X/Y area is a "drag region" where we expect people to drag or press in which case we can instantly start dragging making perceived performance faster.Returns a collection containing the action listeners for this buttonString[]A component may expose mutable property names for a UI designer to manipulate, this API is designed for usage internally by the GUI builder codeClass[]Matches the property names method (see that method for further details).getPropertyValue(String name) Returns the current value of the property name, this method is used by the GUI builderintIndicates a radius in which a pointer release will still have effect.protected voidAllows subclasses to bind functionality that relies on fully initialized and "ready for action" component statebooleanReturns true if this is an auto-released Component.booleanisOff()Checks if the switch is in the "off" position.booleanisOn()Checks if switch is in the "on" position.protected booleanReturns true if the component is interested in receiving drag/pointer release events even after the gesture exceeded its boundaries.booleanisValue()The value of the switchvoidThis method paints the Component on the screen, it should be overriden by subclasses to perform custom drawing or invoke the UI API's to let the PLAF perform the rendering.voidrefreshTheme(boolean merge) Makes sure the component is up to date with the current theme, ONLY INVOKE THIS METHOD IF YOU CHANGED THE THEME!voidRemoves the given action listener from the switchvoidRemoves the given change listener from the switchprotected voidRestores the state of the focusable flag to its default statevoidsetAutoRelease(boolean arg0) Sets the auto released mode of the ComponentvoidsetComponentState(Object state) If getComponentState returned a value the setter can update the value and restore the prior state.voidsetOff()Switches the switch to the "off" position.voidsetOn()Sets the switch to the "on" position.setPropertyValue(String name, Object value) Sets a new value to the given property, returns an error message if failed and null if successful.voidFunction that would be called by the parent Form to put the Component in its released statevoidsetReleaseRadius(int arg0) Indicates a radius in which a pointer release will still have effect.voidsetValue(boolean value) The value of the switchvoidstyleChanged(String propertyName, Style source) Invoked to indicate a change in a propertyName of a StyleMethods inherited from class Component
addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, cancelRepaints, clearClientProperties, contains, containsOrOwns, createStyleAnimation, deinitializeCustomStyle, dragEnter, dragExit, dragFinished, draggingOver, dragInitiated, drawDraggedImage, drop, fireClicked, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBottomGap, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragSpeed, getDragTransparency, getEditingDelegate, getGridPosX, getGridPosY, getHeight, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, getNativeOverlay, getNextFocusDown, getNextFocusLeft, getNextFocusRight, getNextFocusUp, getOuterHeight, getOuterPreferredH, getOuterPreferredW, getOuterWidth, getOuterX, getOuterY, getOwner, getParent, getPreferredH, getPreferredSize, getPreferredSizeStr, getPreferredTabIndex, getPreferredW, getPressedStyle, getPropertyTypeNames, getSameHeight, getSameWidth, getScrollable, getScrollAnimationSpeed, getScrollDimension, getScrollOpacity, getScrollOpacityChangeSpeed, getScrollX, getScrollY, getSelectCommandText, getSelectedRect, getSelectedStyle, getSideGap, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getUIID, getUIManager, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, handlesInput, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initCustomStyle, initDisabledStyle, initLaf, initPressedStyle, initSelectedStyle, initUnselectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditable, isEditing, isEnabled, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isIgnorePointerEvents, isInClippingRegion, isInitialized, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollableX, isScrollableY, isScrollVisible, isSelectableInteraction, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, keyPressed, keyReleased, keyRepeated, laidOut, longKeyPress, longPointerPress, onScrollX, onScrollY, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, paramString, parsePreferredSize, pinch, pinch, pinchReleased, pointerDragged, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerPressed, pointerPressed, pointerReleased, pointerReleased, putClientProperty, refreshTheme, refreshTheme, remove, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, repaint, repaint, requestFocus, respondsToPointerEvents, scrollRectToVisible, scrollRectToVisible, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCellRenderer, setCloudBoundProperty, setCloudDestinationProperty, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setEnabled, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNextFocusDown, setNextFocusLeft, setNextFocusRight, setNextFocusUp, setOpaque, setOwner, setPinchBlocksDragAndDrop, setPreferredH, setPreferredSize, setPreferredSizeStr, setPreferredTabIndex, setPreferredW, setPressedStyle, setRippleEffect, setRTL, setSameHeight, setSameSize, setSameWidth, setScrollAnimationSpeed, setScrollOpacityChangeSpeed, setScrollSize, setScrollVisible, setScrollX, setScrollY, setSelectCommandText, setSelectedStyle, setShouldCalcPreferredSize, setSize, setSmoothScrolling, setSnapToGrid, setTabIndex, setTactileTouch, setTensileDragEnabled, setTensileLength, setTooltip, setTraversable, setUIID, setUIID, setUIIDFinal, setUnselectedStyle, setVisible, setWidth, setX, setY, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, shouldRenderComponentSelection, showNativeOverlay, startEditingAsync, stopEditing, stripMarginAndPadding, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains
-
Constructor Details
-
Switch
public Switch()Default constructor -
Switch
This constructor should be used when customizing theme constants for a different UIID
Parameters
uiid: @param uiid accepts an alternate UIID for switch which might be necessary for theme constants
-
-
Method Details
-
getDragRegionStatus
protected int getDragRegionStatus(int x, int y) Description copied from class:ComponentIndicates if the section within the X/Y area is a "drag region" where we expect people to drag or press in which case we can instantly start dragging making perceived performance faster. This is invoked by the implementation code to optimize drag start behavior
Parameters
-
x: x location for the touch -
y: y location for the touch
Returns
one of the DRAG_REGION_* values
- Overrides:
getDragRegionStatusin classComponent
-
-
styleChanged
Invoked to indicate a change in a propertyName of a Style
NOTE By default this will trigger a call to
Container#revalidate()on the parent container, which is expensive. You can disable this behavior by callingCN.setProperty("Component.revalidateOnStyleChange", "false"). The intention is to change this behavior so that the default is to "not" revalidate on style change, so we encourage you to set this to "false" to ensure for future compatibility.Parameters
-
propertyName: the property name that was changed -
source: The changed Style object
- Specified by:
styleChangedin interfaceStyleListener- Overrides:
styleChangedin classComponent
-
-
calcPreferredSize
Calculates the preferred size based on component content. This method is invoked lazily by getPreferred size.
Returns
the calculated preferred size based on component content
- Overrides:
calcPreferredSizein classComponent
-
resetFocusable
protected void resetFocusable()Restores the state of the focusable flag to its default state- Overrides:
resetFocusablein classComponent
-
refreshTheme
public void refreshTheme(boolean merge) Makes sure the component is up to date with the current theme, ONLY INVOKE THIS METHOD IF YOU CHANGED THE THEME!
Parameters
merge: indicates if the current styles should be merged with the new styles
- Overrides:
refreshThemein classComponent
-
isStickyDrag
protected boolean isStickyDrag()Returns true if the component is interested in receiving drag/pointer release events even after the gesture exceeded its boundaries. This is useful for spinners etc. where the motion might continue beyond the size of the component
Returns
false by default
- Overrides:
isStickyDragin classComponent
-
addActionListener
Adds a listener to the switch which will cause an event to dispatch on click
Parameters
l: implementation of the action listener interface
- Specified by:
addActionListenerin interfaceActionSource
-
removeActionListener
Removes the given action listener from the switch
Parameters
l: implementation of the action listener interface
- Specified by:
removeActionListenerin interfaceActionSource
-
addChangeListener
Adds a listener to the switch which will cause an event on change
Parameters
l: implementation of the action listener interface
-
removeChangeListener
Removes the given change listener from the switch
Parameters
l: implementation of the action listener interface
-
getListeners
Returns a collection containing the action listeners for this button
Returns
the action listeners
Deprecated
This will be removed in a future version.
-
paint
This method paints the Component on the screen, it should be overriden by subclasses to perform custom drawing or invoke the UI API's to let the PLAF perform the rendering.
Parameters
g: the component graphics
-
initComponent
protected void initComponent()Allows subclasses to bind functionality that relies on fully initialized and "ready for action" component state- Overrides:
initComponentin classComponent
-
deinitialize
protected void deinitialize()Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy. This allows the component to deregister animators and cleanup after itself. This method is the opposite of the initComponent() method.- Overrides:
deinitializein classComponent
-
isValue
public boolean isValue()The value of the switch
Returns
the value
-
setValue
public void setValue(boolean value) The value of the switch
Parameters
value: the value to set
-
isOn
public boolean isOn()Checks if switch is in the "on" position.
Returns
True if switch is on.
-
setOn
public void setOn()Sets the switch to the "on" position. -
isOff
public boolean isOff()Checks if the switch is in the "off" position.
Returns
True of switch is currently off.
-
setOff
public void setOff()Switches the switch to the "off" position. -
getPropertyNames
A component may expose mutable property names for a UI designer to manipulate, this API is designed for usage internally by the GUI builder code
Returns
the property names allowing mutation
- Overrides:
getPropertyNamesin classComponent
-
getComponentState
Some components may optionally generate a state which can then be restored using setCompnentState(). This method is used by the UIBuilder.
Returns
the component state or null for undefined state.
- Overrides:
getComponentStatein classComponent
-
setComponentState
If getComponentState returned a value the setter can update the value and restore the prior state.
Parameters
state: the non-null state
- Overrides:
setComponentStatein classComponent
-
getPropertyTypes
Matches the property names method (see that method for further details).
Returns
the types of the properties
- Overrides:
getPropertyTypesin classComponent
-
getPropertyValue
Returns the current value of the property name, this method is used by the GUI builder
Parameters
name: the name of the property
Returns
the value of said property
- Overrides:
getPropertyValuein classComponent
-
setPropertyValue
Sets a new value to the given property, returns an error message if failed and null if successful. Notice that some builtin properties such as "$designMode" might be sent to components to indicate application state.
Parameters
-
name: the name of the property -
value: new value for the property
Returns
error message or null
- Overrides:
setPropertyValuein classComponent
-
-
isAutoRelease
public boolean isAutoRelease()Returns true if this is an auto-released Component. An Auto-released Component will be disarmed when a drag is happening within it- Specified by:
isAutoReleasein interfaceReleasableComponent
-
setAutoRelease
public void setAutoRelease(boolean arg0) Sets the auto released mode of the Component- Specified by:
setAutoReleasein interfaceReleasableComponent
-
getReleaseRadius
public int getReleaseRadius()Indicates a radius in which a pointer release will still have effect. Notice that this only applies to pointer release events and not to pointer press events
Returns
the releaseRadius
- Specified by:
getReleaseRadiusin interfaceReleasableComponent
-
setReleaseRadius
public void setReleaseRadius(int arg0) Indicates a radius in which a pointer release will still have effect. Notice that this only applies to pointer release events and not to pointer press events
Parameters
releaseRadius: the releaseRadius to set
- Specified by:
setReleaseRadiusin interfaceReleasableComponent
-
setReleased
public void setReleased()Function that would be called by the parent Form to put the Component in its released state- Specified by:
setReleasedin interfaceReleasableComponent
-