A simple and customizable two or three states Switch View

Related tags

UI/UX RMSwitch
Overview

RMSwitch

A simple View that works like a switch, but with more customizations.
With the option to choose between two or three states. (from v1.1.0)

** If you're upgrading from a version < 1.2.0, check the changelog of the 1.2.0 version, there are breaking changes!

[Changelog] (CHANGELOG.md)

From version 1.2.0 you can choose between three switch design:

-"Slim"
-"Large"
-"Android"

Download

Gradle:

compile 'com.rm:rmswitch:1.2.2'

Min API level: 16 (Android 4.1)

Usage

To use them, just add this to your layout file

    <!-- Two states switch -->
    <com.rm.rmswitch.RMSwitch
                android:id="@+id/your_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                
                app:checked="true"
                app:forceAspectRatio="false"
                app:enabled="true"
                app:switchDesign="android"
                app:switchBkgCheckedColor="@color/green"
                app:switchBkgNotCheckedColor="@color/red"
                app:switchToggleCheckedColor="@color/green"
                app:switchToggleCheckedImage="@drawable/happy"
                app:switchToggleNotCheckedColor="@color/red"
                app:switchToggleNotCheckedImage="@drawable/sad"/>
                
    <!-- Three states switch -->                
    <com.rm.rmswitch.RMTristateSwitch
                android:id="@+id/your_id2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                
                app:forceAspectRatio="false"
                app:state="left"
                app:enabled="true"
                app:switchDesign="large"
                app:switchBkgLeftColor="@color/red"
                app:switchBkgMiddleColor="@color/grey"
                app:switchBkgRightColor="@color/green"
                app:switchToggleLeftColor="@color/red"
                app:switchToggleLeftImage="@drawable/sad"
                app:switchToggleMiddleColor="@color/grey"
                app:switchToggleMiddleImage="@drawable/neutral"
                app:switchToggleRightColor="@color/green"
                app:switchToggleRightImage="@drawable/happy"/>

... if you need to use this View's custom xml attributes (shown in a table below or in the example above) do not forget to add this to your root layout

xmlns:app="http://schemas.android.com/apk/res-auto"

To see how it looks in the preview screen of Android Studio, build your project first

And this in your Activity

public class MainActivity extends AppCompatActivity {
    RMSwitch mSwitch;
    RMTristateSwitch mTristateSwitch;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mSwitch = (RMSwitch) findViewById(R.id.your_id);
        mTristateSwitch = (RMTristateSwitch) findViewById(R.id.your_id2);
        
        
        // Setup the switch
        mSwitch.setChecked(true);
        mSwitch.setEnabled(true);
        mSwitch.setForceAspectRatio(false);
        mSwitch.setSwitchBkgCheckedColor(Color.GREEN);
        mSwitch.setSwitchBkgNotCheckedColor(Color.RED);
        mSwitch.setSwitchToggleCheckedColor(Color.BLACK);
        mSwitch.setSwitchToggleNotCheckedColor(Color.BLACK);
        mSwitch.setSwitchDesign(RMTristateSwitch.DESIGN_ANDROID);
        
        
        // You can choose if use drawable or drawable resource
        //mSwitch.setSwitchToggleCheckedDrawableRes(android.R.drawable.ic_media_next);
        mSwitch.setSwitchToggleCheckedDrawable(ContextCompat.getDrawable(this, android.R.drawable.ic_media_next));
        
        //mSwitch.setSwitchToggleNotCheckedDrawableRes(android.R.drawable.ic_media_previous);
        mSwitch.setSwitchToggleNotCheckedDrawable(ContextCompat.getDrawable(this, android.R.drawable.ic_media_previous));
        
        
        // Setup the tristate switch
        mTristateSwitch.setState(RMTristateSwitch.STATE_LEFT);
        mTristateSwitch.setForceAspectRatio(true);
        mTristateSwitch.setEnabled(true);
        mTristateSwitch.setRightToLeft(false);
        mTristateSwitch.setSwitchDesign(RMTristateSwitch.DESIGN_LARGE);
        mTristateSwitch.setSwitchToggleLeftColor(Color.DKGRAY);
        mTristateSwitch.setSwitchToggleMiddleColor(Color.DKGRAY);
        mTristateSwitch.setSwitchToggleRightColor(Color.DKGRAY);
        mTristateSwitch.setSwitchBkgLeftColor(Color.LTGRAY);
        mTristateSwitch.setSwitchBkgMiddleColor(Color.LTGRAY);
        mTristateSwitch.setSwitchBkgRightColor(Color.LTGRAY);
        
        
        // You can choose if use drawable or drawable resource
        //mTristateSwitch.setSwitchToggleLeftDrawableRes(android.R.drawable.ic_media_previous);
        mTristateSwitch.setSwitchToggleLeftDrawable(ContextCompat.getDrawable(this, android.R.drawable.ic_media_previous));
        
        //mTristateSwitch.setSwitchToggleMiddleDrawableRes(android.R.drawable.ic_media_play);
        mTristateSwitch.setSwitchToggleMiddleDrawable(ContextCompat.getDrawable(this, android.R.drawable.ic_media_play));
        
        //mTristateSwitch.setSwitchToggleRightDrawableRes(android.R.drawable.ic_media_next);
        mTristateSwitch.setSwitchToggleRightDrawable(ContextCompat.getDrawable(this, android.R.drawable.ic_media_next));
        
        
        // Add a Switch state observer
        mSwitch.addSwitchObserver(new RMSwitch.RMSwitchObserver() {
            @Override
            public void onCheckStateChange(RMSwitch switchView, boolean isChecked) {
                                Toast.makeText(MainActivity.this, 
                                        "Switch state: " + 
                                        (isChecked ? "checked" : "not checked"), Toast.LENGTH_LONG)
                                        .show();
            }
        });
        
        mTristateSwitch.addSwitchObserver(new RMTristateSwitch.RMTristateSwitchObserver() {
            @Override
            public void onCheckStateChange(RMTristateSwitch switchView, @RMTristateSwitch.State int state) {
                Toast
                        .makeText(MainActivity.this,
                                state == RMTristateSwitch.STATE_LEFT ?
                                        "Left" :
                                        state == RMTristateSwitch.STATE_MIDDLE ?
                                                "Middle" :
                                                "Right",
                                Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Supported Attributes

RMSwitch

XML Attribute Java method Description Default value
checked setChecked(boolean checked) The initial state of the Switch, if checked or not false
enabled setEnabled(boolean enabled) If not enabled, the Switch will not be clickable, but it is still possible to change its state programmatically true
forceAspectRatio setForceAspectRatio(boolean forceAspectRatio) Force the Switch aspect ratio true
switchBkgCheckedColor setSwitchBkgCheckedColor(@ColorInt int color) The background color of the Switch if checked your current theme colorControlHighlight attribute
switchBkgNotCheckedColor setSwitchBkgNotCheckedColor(@ColorInt int color) The background color of the Switch if not checked the same as switchBkgCheckedColor
switchToggleCheckedColor setSwitchToggleCheckedColor(@ColorInt int color) The color of the Switch toggle if checked your current theme colorAccent attribute
switchToggleNotCheckedColor setSwitchToggleNotCheckedColor(@ColorInt int color) The color of the Switch toggle if not checked white
switchToggleCheckedImage setSwitchToggleCheckedDrawableRes(@DrawableRes int drawable) The image to be shown on the toggle if checked the same as switchToggleNotCheckedImage if set, none otherwise
setSwitchToggleCheckedDrawable(Drawable drawable)
switchToggleNotCheckedImage setSwitchToggleNotCheckedDrawableRes(@DrawableRes int drawable) The image to be shown on the toggle if not checked the same as switchToggleCheckedImage if set, none otherwise
setSwitchToggleNotCheckedDrawable(Drawable drawable)
switchDesign setSwitchDesign(@SwitchDesign int switchDesign) The switch design, one of the RMAbstractSwitch.DESIGN_*** constants, changes the appearance of the switch RMAbstractSwitch.DESIGN_LARGE

RMTristateSwitch

XML Attribute Java method Description Default value
state setState(@State int state) The initial state of the Switch, if left, middle or right left
enabled setEnabled(boolean enabled) If not enabled, the Switch will not be clickable, but it is still possible to change its state programmatically true
forceAspectRatio setForceAspectRatio(boolean forceAspectRatio) Force the Switch aspect ratio true
right_to_left setRightToLeft(boolean rightToLeft) The direction of the switch at every tap, if from left to right or right to left false
switchBkgLeftColor setSwitchBkgLeftColor(@ColorInt int color) The background color of the Switch if in the left state your current theme colorControlHighlight attribute
switchBkgMiddleColor setSwitchBkgMiddleColor(@ColorInt int color) The background color of the Switch if in the middle state the same as switchBkgLeftColor
switchBkgRightColor setSwitchBkgRightColor(@ColorInt int color) The background color of the Switch if in the right state the same as switchBkgLeftColor
switchToggleLeftColor setSwitchToggleLeftColor(@ColorInt int color) The background color of the Switch if in the left state white
switchToggleMiddleColor setSwitchToggleMiddleColor(@ColorInt int color) The background color of the Switch if in the middle state your current theme primaryColor attribute
switchToggleRightColor setSwitchToggleRightColor(@ColorInt int color) The background color of the Switch Toggle if in the right state your current theme accentColor attribute
switchToggleLeftImage setSwitchToggleLeftDrawableRes(@ColorInt int color) The toggle image of the Switch if in the left state the same as the one of the other states toggle image if at least one set, none otherwise
setSwitchToggleLeftDrawable(Drawable drawable)
switchToggleMiddleImage setSwitchToggleMiddleDrawableRes(@ColorInt int color) The toggle image of the Switch if in the middle state the same as the one of the other states toggle image if at least one set, none otherwise
setSwitchToggleMiddleDrawable(Drawable drawable)
switchToggleRightImage setSwitchToggleRightDrawableRes(@ColorInt int color) The toggle image of the Switch if in the right state the same as the one of the other states toggle image if at least one set, none otherwise
setSwitchToggleRightDrawable(Drawable drawable)
switchDesign setSwitchDesign(@SwitchDesign int switchDesign) The switch design, one of the RMAbstractSwitch.DESIGN_*** constants, changes the appearance of the switch RMAbstractSwitch.DESIGN_LARGE

The changes between the Switch states will be automatically cross-faded, to obtain a smooth experience

License

Copyright 2017 Riccardo Moro.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and 
limitations under the License.
Comments
  • Bug: in sample, crash when pressing home button

    Bug: in sample, crash when pressing home button

    This is the log:

    11-21 10:10:47.451 4055-4055/com.rm.switchsample E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 1160672) 11-21 10:10:47.453 4055-4055/com.rm.switchsample E/AndroidRuntime: FATAL EXCEPTION: main Process: com.rm.switchsample, PID: 4055 java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 1160672 bytes at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3755) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6088) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) Caused by: android.os.TransactionTooLargeException: data parcel size 1160672 bytes at android.os.BinderProxy.transactNative(Native Method) at android.os.BinderProxy.transact(Binder.java:615) at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3628) at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3747) at android.os.Handler.handleCallback(Handler.java:751)  at android.os.Handler.dispatchMessage(Handler.java:95)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6088)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

    bug 
    opened by AndroidDeveloperLB 20
  • Crashes on start

    Crashes on start

    Title says it all

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rm.switchsample/com.rm.switchsample.ActivityMain}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.rm.rmswitch.RMSwitch at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.rm.rmswitch.RMSwitch Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.rm.rmswitch.RMSwitch Caused by: java.lang.reflect.InvocationTargetException

    opened by Akshshr 6
  • strange loop if in relative layout

    strange loop if in relative layout

    ....android E/RMSwitch: Paddings ....android E/RMSwitch: Margins ....android E/RMSwitch: Paddings ....android E/RMSwitch: Margins ....android E/RMSwitch: Paddings ....android E/RMSwitch: Margins ....android E/RMSwitch: Paddings ....android E/RMSwitch: Margins ....android E/RMSwitch: Paddings ....android E/RMSwitch: Margins

    opened by ksatalsin 3
  • [request] custom background

    [request] custom background

    It will be great to have a possibility to add custom background to the switch. Or have material switch background with possibility to add drawable to left and right.

    enhancement 
    opened by wrozwad 3
  • Memory leak caused by static variables

    Memory leak caused by static variables

    Hi, thanks for the library. However it has a potential problem causing memory leaks. Here is a Leak Canary dump showing how the memory leak occured.

    Could you fix it please ? screen shot 2017-10-22 at 3 09 21 pm

    opened by CROSP 1
  • On adapter.notifyDataSetChanged all switches are animated

    On adapter.notifyDataSetChanged all switches are animated

    I have a RecyclerView, each item have a RMTristateSwitch, when update all data, I call to adapter.notifyDataSetChanged() and all RMTristateSwitch do an animation and it's very ugly. ¿How can I disabled this animation on reload?

    opened by djardon 1
  • Cannot use checked image

    Cannot use checked image

    It is working fine when I am not using image for checked state but when I use is it is giving error. I am using it in Toolbar the code is following <com.rm.rmswitch.RMSwitch android:id="@+id/btnAvailability" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="@dimen/margin_8dp" app:checked="true" app:switchBkgCheckedColor="@color/colorWhite" app:switchBkgNotCheckedColor="@color/colorWhite" app:switchToggleCheckedColor="@color/colorGreen" app:switchToggleCheckedImage="@drawable/confirm" app:switchToggleNotCheckedImage="@drawable/cancel" app:switchToggleNotCheckedColor="@color/colorPrimary" />

    Caused by: android.view.InflateException: Binary XML file line #38: Error inflating class com.rm.rmswitch.RMSwitch at android.view.LayoutInflater.createView(LayoutInflater.java:649) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:768) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:708) at android.view.LayoutInflater.rInflate(LayoutInflater.java:839) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802) at android.view.LayoutInflater.rInflate(LayoutInflater.java:842) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802) at android.view.LayoutInflater.parseInclude(LayoutInflater.java:975) at android.view.LayoutInflater.rInflate(LayoutInflater.java:835) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802) at android.view.LayoutInflater.rInflate(LayoutInflater.java:842) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802) at android.view.LayoutInflater.rInflate(LayoutInflater.java:842) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802) at android.view.LayoutInflater.rInflate(LayoutInflater.java:842) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802) at android.view.LayoutInflater.inflate(LayoutInflater.java:519) Caused by: java.lang.NumberFormatException: Invalid int: "res/drawable/confirm.png" at java.lang.Integer.invalidInt(Integer.java:138) at java.lang.Integer.parse(Integer.java:410) at java.lang.Integer.parseInt(Integer.java:367) at com.android.internal.util.XmlUtils.convertValueToInt(XmlUtils.java:133) at android.content.res.TypedArray.getInt(TypedArray.java:357) at com.rm.rmswitch.RMAbstractSwitch.(RMAbstractSwitch.java:119) at com.rm.rmswitch.RMSwitch.(RMSwitch.java:87) at com.rm.rmswitch.RMSwitch.(RMSwitch.java:83)

    opened by kauramanp 0
  •  switch button looping

    switch button looping

    android switch loop does a iteration in 3... if you are calling an api it will call it 3 times, toasting 3 times. after the second time the toggle goes from on - off - on again.

    opened by melatgenius 0
  • Weird behavior when using with ViewPager

    Weird behavior when using with ViewPager

    When using the RMSwitch with a ViewPager and a RecyclerView, the switches on the adjacent screen are showing incorrectly. The drawables are rendered incorrectly and clicking it does not move to the other side. See the attached picture, screenshot

    The workaround is to reload the entire recyclerview by calling notifyDataSetChanged() but I prefer not to do that since it has a visible flash in the data.

    opened by akashpathak 7
  • Ability to setChecked without animation

    Ability to setChecked without animation

    When I call setChecked inside a RecyclerView, the animation triggers when I don't want it to. Can you please make a method such as setChecked(boolean checked, boolean animate)?

    enhancement 
    opened by akashpathak 1
Owner
Riccardo Moro
Just an Android developer and enthusiast
Riccardo Moro
A material Switch with icon animations and color transitions

Material Animated Switch A material Switch with icon animations and color transitions Sample video: Youtube Material Animated Switch video Sample app:

Adrián Lomas 1.2k Dec 29, 2022
Name UI states, navigate between them, remember where you've been.

Deprecated Flow had a good run and served us well, but new use is strongly discouraged. The app suite at Square that drove its creation is in the proc

Square 2.8k Dec 29, 2022
A simple, customizable and easy to use swipeable view stack for Android.

SwipeStack A simple, customizable and easy to use swipeable view stack for Android. QuickStart Include the Gradle dependency dependencies { compil

Frederik Schweiger 1.5k Dec 30, 2022
A customizable debug screen to view and edit flags that can be used for development in Jetpack Compose applications

Tweaks A customizable debug screen to view and edit flags that can be used for development in Jetpack Compose applications To include the library add

Guillermo Merino Jiménez 4 Jan 14, 2022
Customizable Item Setting View Android

ItemSettingView Simple ItemSettingView and Custom Installation Add it in your root build.gradle at the end of repositories: allprojects { reposito

Andhika Yuana 15 Aug 19, 2022
Fully customizable implementation of "Snowfall View" on Android.

Android-Snowfall Fully customizable implementation of "Snowfall View" on Android. That's how we use it in our app Hotellook Compatibility This library

Jetradar Mobile 1.2k Dec 21, 2022
Android View for displaying and selecting values in a circle-shaped View, with animations and touch gestures.

CircleDisplay Android View for displaying and selecting (by touch) values / percentages in a circle-shaped View, with animations. Features Core featur

Philipp Jahoda 287 Nov 18, 2022
A nicer-looking, more intuitive and highly customizable alternative for radio buttons and dropdowns for Android.

SwipeSelector Undergoing for some API changes for a 2.0 major version, see example usage in the sample module! What and why? Bored of dull looking rad

Iiro Krankka 1.1k Dec 30, 2022
The CustomCalendarView provides an easy and customizable calendar to create a Calendar. It dispaly the days of a month in a grid layout and allows to navigate between months

Custom-Calendar-View To use the CustomCalendarView in your application, you first need to add the library to your application. You can do this by eith

Nilanchala Panigrahy 113 Nov 29, 2022
:balloon: A lightweight popup like tooltips, fully customizable with an arrow and animations.

Balloon ?? A lightweight popup like tooltips, fully customizable with arrow and animations. Including in your project Gradle Add below codes to your r

Jaewoong Eum 2.8k Jan 5, 2023
⚡️A highly customizable, powerful and easy-to-use alerting library for Android.

Flashbar A highly customizable, powerful and easy-to-use alerting library for Android. Specs This library allows you to show messages or alerts in you

Aritra Roy 1.7k Dec 7, 2022
FloatingView can make the target view floating above the anchor view with cool animation

FloatingView FloatingView can make the target view floating above the anchor view with cool animation Links 中文版 README Blog about FloatingView demo.ap

UFreedom 1.8k Dec 27, 2022
用于做Path动画的自定义View。 I have a path.I have a view. (Oh~),Path(Anim)View.

PathAnimView 用于做Path动画的自定义View。 I have a path.I have a view. (Oh~),Path(Anim)View. 现已经找到图片->SVG->PATH的正确姿势, Now i have a pic.I have a view. Oh~,Path(A

张旭童 1.1k Oct 28, 2022
Highly customizable SlidingLayer as you have seen in Wunderlist

6Wunderkinder SlidingLayer for Android This repository hosts a library that provides an easy way to include an autonomous layer/view that slides from

Microsoft Archive 942 Nov 28, 2022
Highly customizable SlidingLayer as you have seen in Wunderlist

6Wunderkinder SlidingLayer for Android This repository hosts a library that provides an easy way to include an autonomous layer/view that slides from

Microsoft Archive 942 Nov 28, 2022
Snake View is a simple and animated linear chart for Android.

Snake View Snake library is a simple and animation line chart for Android. Latest Version How to use Configuring your project dependencies Add the lib

Txus Ballesteros 339 Dec 14, 2022
A simple library to let you sign (or draw lines) smoothly with your finger into a view and save it.

FingerSignView Introduction FingerSignView is a simple library that lets you finger, or draw lines, smoothly with your finger into a View and save it

Agnaldo Pereira 25 Nov 20, 2022
Simple View to change Brush Size, Alpha and Color

BrushView Simple View to change Brush Size, Alpha and Color Screenshots How to install In your build.gradle project allprojects { repositories {

Andres Ruiz 16 Jun 28, 2018
A simple and Elegant Showcase view for Android

Tuto Showcase A simple and Elegant Showcase view for Android TutoShowcase.from(this) .setContentView(R.layout.tuto_sample) .on(R.id.about) //

Florent CHAMPIGNY 509 Nov 25, 2022