A cute widget of Switch Button for you to create beautiful and friendly UI.

Overview

SwitchButton

Android Arsenal

To get a quick preview, you can get Demo apk in Google Play or Directly download.

This project provides you a convenient way to use and customise a SwitchButton widget in Android.


Change Log

All Change Log

Some attributes are changed in 2.0.0 and you need to update them to the new ones, since the measurement logic has been totally changed. (Default behavior and style does not change.)

因为2.0.0测量逻辑的改变,部分属性已经做了修改,请更新到新的属性。(默认行为和样式并没有变化)

  1. Re-clarify the meaning of some params.
  2. Update the measurement of SwitchButton and the logic becomes more clear, especially the text part.
  3. Support config SwitchButton's size by setting a exact width and height. There are now TWO mainly method to control it's size.
  4. When use SwitchButon in a scrollable view, SwitchButton consume scroll gestures only horizontal. This means the when you want to scroll the scrollable view vertically and start your touch on a SwitchButton, it will not stop you now.
  5. Bug fix.
  1. 重新明确了参数的含义。
  2. 更新了SwitchButton的测量机制,逻辑更加清晰;尤其是文字部分。
  3. 支持设置确定的宽高,来确定SwitchButton的View大小。现在有两种方式可以控制SwitchButton的大小了。
  4. 可滚动的View中的SwitchButton只会消费横向滚动事件。这意味着你可以从SwitchButton开始按下并纵向滚动可滚动View,SwitchButton现在不会阻止你滚动了。
  5. Bug 修复。

Using SwitchButton in your application

In Gradle ​ Add dependencies in build.gradle of your module

	dependencies {
		implementation 'com.kyleduo.switchbutton:library:2.0.3'
	}

Migrate to 2.0.0 (迁移到2.0.0)

ENG

There is a big diagram below to show how SwitchButton measure it self in 2.0.0. It is strongly recommended that you should check it out.

  1. kswBackMeasureRatio has been removed from SwitchButton attributes since it has an ambiguous meaning. I've add the new kswThumbRangeRatio attribute to represent how much multiple the scroll range of thumb than the width of thumb.
  2. kswTextMarginH and kswAutoAdjustTextPosition have been removed from SwitchButton attributes since I updated the measurement logic of text part. And these two attributes do not represent the back meaning well. kswTextThumbInset, kswTextExtra and kswTextAdjust was introduced to represent "how much the text go under thumb", "how much extra space do you want around the text" and "how much to move the text from the center of text area to adjust the text's position". There are all shown on the diagram.
  3. Setters and getters are also changed due to the change of attributes.

CHN

下面有一张图表来解释SwitchButton在2.0.0版本中是如何进行测量的,非常建议你看一看。

  1. kswBackMeasureRatio 属性被移除了,因为名称有歧义。新增加的 kswThumbRangeRatio 属性表示thumb移动区域和thumb宽度的比值。
  2. kswTextMarginHkswAutoAdjustTextPosition 属性被移除了,因为我更新了对文字的测量逻辑,而且这两个属性名称表意不明确。我增加了kswTextThumbInset, kswTextExtrakswTextAdjust 这三个新属性来分别表示“文字在thumb下面的距离”,“额外文字空间”和”文字调节距离“。这些都在图表中有所体现。
  3. setter和getter都跟随属性名称的改变而进行了改变。

Diagram: How SwitchButton Measure

This diagram shows how SwitchButton measure itself and what does those nouns mean. To measure width is much complex than the height, so if you know how to measure width, you know how to measure height. And text measurement and location increase the complexity.

demo_preview


Demo

I create a new demo apk to show you how to style the cute widget and use it. There's some screenshots of the new demo.

demo_preview


Usage

The usage of SwitchButton is just like CheckBox. The basic control APIs of SwitchButton.

  • setChecked(boolean)
  • toggle()

Since SwitchButton has addition animation when checked status changed, there are two addition methods for disable animation for single operation.

  • setCheckedImmediately(boolean): like setChecked but NO animation.
  • toggleImmediately(): like toggle but NO animation.

From version 1.4.1 on, SwitchButton support operation without onCheckedChanged callback. It makes changing state in code more convenient. Using these methods to achieve that feature.

  • setCheckedNoEvent(boolean)
  • setCheckedImmediatelyNoEvent(boolean)
  • toggleNoEvent()
  • toggleImmediatelyNoEvent()

Style

In 1.3.0, I updated the usage of SwitchButton library. To make it more Android way to use, I've combined the thumb and back style each to StateListColor/StateListDrawable. So you are free to create styles in different states.

In xml layout file, you can configure the face of switch button using these attrs.

  • kswThumbDrawable: drawable for thumb
  • kswThumbColor: color for thumb
  • kswThumbMargin: margin from thumb to back, can be negative. maybe cover by single direction margins
  • kswThumbMarginTop: same to kswThumbMargin, just top
  • kswThumbMarginBottom: same to kswThumbMargin, just bottom
  • kswThumbMarginLeft: same to kswThumbMargin, just left
  • kswThumbMarginRight: same to kswThumbMargin, just right
  • kswThumbWidth: width of thumb
  • kswThumbHeight: height of thumb
  • kswThumbRadius: radius of thumb rect, only work with kswThumbColor
  • kswBackRadius: radius of background rect, only work with kswBackColor
  • kswBackDrawable: drawable for background
  • kswBackColor: color for background
  • kswFadeBack: fade background color/drawable when drag or animate between on/off status or not
  • kswAnimationDuration: duration of animation between 2 status
  • kswTintColor: change SwitchButton's style just by one property, all relevant color will be generate automatically. Do not support SwitchButtonMD or other style created by xml resources.
  • kswTextOn: text for checked status.
  • kswTextOff: text for unchecked status.
  • kswTextThumbInset (since 2.0.0): length of the part of text under the thumb.
  • kswTextExtra (since 2.0.0): extra space needed by background besides the actual text width.
  • kswTextAdjust (since 2.0.0): move the text after position text on the center of text area.
  • kswThumbRangeRatio (since 2.0.0): (thumb move range width / thumb's width). float value. see measure diagram
  • kswBackMeasureRatio: (background's width / thumb's width). float value. Removed since 2.0.0
  • kswTextMarginH: horizontal margin of text. Removed since 2.0.0
  • kswAutoAdjustTextPosition: (since 1.4.4) whether auto adjust text position to make them looks centered (NOT really centered) when there are round corners. You should set this to false when you don't need this feature. Removed since 2.0.0

You can alse change the configuration of SwitchButton in code. You can find the api from Demo apk. There's a glance.

private String[] opts = new String[]{
			"setThumbColorRes/setThumbColor",
			"setThumbDrawableRes/setThumbDrawable",
			"setBackColorRes/setBackColor",
			"setBackDrawableRes/setBackDrawable",
			"setTintColor",
			"setThumbMargin",
			"setThumbSize",
			"setThumbRadius (color-mode only)",
			"setBackRadius (color-mode only)",
			"setFadeBack",
			"setBackMeasureRatio",
			"setAnimationDuration",
			"setDrawDebugRect",
			"setText",
	};

Beautiful Apps

If you're using SwitchButton in your app, wish you can email me these infomation of your app and I'll create a list here. And that should be an utmost encouragement to me. :-) [email protected]

App Name Description Markets Developer
headlines.png Headlines Headlines is a news dashboard for your smart TV. market_logo_google_play.pngamazon-underground-app-us-black.png MYSTRAL
lantouzi.png 懒投资 专业安全的投资理财平台 官方网站 懒投资 lantouzi.com
notifications_in_bubble.png Notifications in bubble Access all notifications from a floating bubble. market_logo_google_play.png BestAppzz

License

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
  • setText(.., ...) doesn't call

    setText(.., ...) doesn't call "invalidate()"

    When setting the text in code, invalidate() isn't called (just requestLayout()), which doesn't redraw the text. I would suggest calling both invalidate() and requestLayout(), as explained here: Why is requestLayout being called directly after invalidate?

    Also, if I set a text with xml attributes (kswTextOn), the text will be centered. Now, if I update the text in code, the text will keep the position of the initial text and won't look great.

    bug 
    opened by jbiral 8
  • Demo App can not work in RedMI2(红米2)

    Demo App can not work in RedMI2(红米2)

    Once SwitchButton is placed in ScrollView(activity_use.xml), it can not slide after click and only splash like a button. I imported your project and built the demo app with Android Studio without changing any code.

    当把 SwitchButton 放在ScrollView的LinearLayout中时(activity_use.xml),就只能像按钮一样响应点击并且只闪一下,不能自动滑动上面的滑块,也很难把滑块滑走。 在Nexus 6(android 5.1)上也一样,Easy to use中的SwitchButton都不能正常工作。

    opened by ccc-rrr 8
  • Library still failed in drawableStateChanged() if getted by gradle

    Library still failed in drawableStateChanged() if getted by gradle

    Hello.

    Issue https://github.com/kyleduo/SwitchButton/issues/13 was fixed in repository, but gradle download non fixed version.

    Is available use compile 'com.kyleduo.switchbutton:library:1.2.9' or higher?

    opened by andrianovs 8
  • Not able to set size for iOS switch

    Not able to set size for iOS switch

    I copied and pasted code from your sample into my app, however the switch is appearing kind of huge screen shot 2016-07-05 at 4 23 23 pm

    Is there a way to control the size of the switch? I need it to be smaller.

    opened by rahulchowdhury 7
  • Toggling with finger or mouse doesn't work

    Toggling with finger or mouse doesn't work

    This library looks useful and I could surely use it in my project but maybe I'm doing something wrong?

    I programmatically created an instance of SwitchButton like so:

    SwitchButton toggle = new SwitchButton(this);
    

    I then setup the layout so the switch appears on screen using code.

    I see my switch in the center of my screen but trying to drag it or tapping on the switch using my finger doesn't toggle the switch.

    I ran the app on the Android emulator too and tried using the mouse to click on the switch, nothing changes. The switch is still in the disabled state.

    What am I doing wrong?

    Project Settings Using Android API level 19 (KitKat 4.4+) AndroidCompat enabled

    opened by chewedon 5
  • setTintColor() makes Thumb get big

    setTintColor() makes Thumb get big

    Hello!

    I am testing changing the tint color programmatically with setTintColor but when I run the app, the thumb turns so big that it doesn't looks nice. I don't know why it changes it size. If i set the tint via xml, is working good.

    Do I have to set some parameters up in order to setTintColor work properly? Thanks!

    My XML <com.kyleduo.switchbutton.SwitchButton android:id="@+id/indicator_switch" android:layout_width="match_parent" style="@style/SwitchButtonMD" app:kswTintColor="@color/teal" android:layout_height="wrap_content" android:layout_weight="1" android:layout_gravity="right" android:gravity="right"/>

    My Java:

    login_remember_me.setTintColor(getResources().getColor(R.color.red));

    Big thumb image

    screen shot 2016-05-09 at 2 09 02 pm

    opened by jgutierrez11 5
  • how can i set checked without callback?

    how can i set checked without callback?

    update 1.2.6 With calling the method setChecked(boolean, false);, you can change the status without invoking the listener.

    there is the method setChecked(boolean, false) in the 1.2.6, but no longer in 1.4.0, so what should i do when i want to modify the check status whitout callback?

    opened by 531227501 4
  • SwichButton高度问题

    SwichButton高度问题

    SwichButton的宽高都设置为wrap_content的时候,SwichButton上面和下面都有白色的边距,就像设置了padding_top和padding_bottom一样,而且上下的边距不相等,无法设置SwichButton在水平方向的LinearLayout中垂直居中显示,希望楼主能解决

    opened by gh4work 4
  • hi,i have some question for custom switch button.

    hi,i have some question for custom switch button.

    how to custom switch track height , seems track height cant change, same height as button icon .

    my english not good,but hope you can help me. thx. :)

    opened by wozuihighwa 4
  • NullPointerException in SwitchButton.drawableStateChanged()

    NullPointerException in SwitchButton.drawableStateChanged()

    Hi there!

    I've got an issue with NullPointerException in SwitchButton.drawableStateChanged() - mConf is not initialized. When I do android:enabled="false" in XML then drawableStateChanged() is calling before initView(). Because of there is super(context, attrs, defStyle) in constructor of course.

    When I use setEnabled(false) for SwitchButton in code all work right.

    opened by paraddiz 4
  • Failed build after removing jcenter() and changing to mavenCentral()

    Failed build after removing jcenter() and changing to mavenCentral()

    jcenter() have been deprecated recently, and after replacing it with mavenCentral(), project build failed with error "could not find com.kyleduo.switchbutton:library:2.0.3

    opened by sca0610 3
  • How to change kswtintcolor to gradiant color attribute... It generate error when i use it.

    How to change kswtintcolor to gradiant color attribute... It generate error when i use it.

    Binary XML file line #75: Error inflating class com.kyleduo.switchbutton.SwitchButton Caused by: android.view.InflateException: Binary XML file line #75: Error inflating class com.kyleduo.switchbutton.SwitchButton

    opened by kiransharmaaa 0
Owner
kyleduo
A mobile application developer, who aim to make wonderful product.
kyleduo
AwesomeSwitch is a replacement for the standard Switch(View) android offers, and it offers much more customization than the standard switch component.

AwesomeSwitch AwesomeSwitch is a replacement for the standard Switch(View) android offers, and it offers much more customization than the standard swi

Anoop S S 29 Jun 2, 2022
Base on android-process-button this is the advanced version of the android-process-button.

Rock Button release log Base on android-process-button this is the advanced version of the android-process-button ##Main Features ActionProcessButton

MDCCLXXVI KPT 119 Nov 25, 2022
Circle button widget for Android

DEPRECATED This library is deprecated and no new development is taking place. Consider using a FAB(Floating action button) instead. E.g. the Android D

Markus Hintersteiner 1.5k Dec 9, 2022
Google launcher-style implementation of switch (enable/disable) icon

Android-SwitchIcon Google launcher-style implementation of switch (enable/disable) icon Compatibility This library is compatible from API 15 (Android

Zagumennyi Evgenii 2.3k Dec 17, 2022
A lightweight iOS switch view style for Android

iOS-SwitchView A lightweight iOS switch view style for Android Usage Add SwitchView into xml layout <vn.luongvo.widget.iosswitchview.SwitchView an

Luong Vo (Lucas) 72 Nov 5, 2022
comtomize view submit button which you use for submit operation or download operation and so on.

This is library project with a custom view that implements concept of Submit Button (https://dribbble.com/shots/1426764-Submit-Button?list=likes&offse

ZhangLei 129 Feb 5, 2021
A widget you can slide it to open or close something

SlideSwitch About SlideSwitch A button that you can slide on or off How to import into your project Android Studio use gradle. Gradle dependency: Add

Quinn 539 Jul 12, 2022
Button for android with animations for transition and error states.

Transition Button Android Preview Expand animation: Shake animation: Installation Gradle dependencies { implementation 'com.royrodriguez:transitionbu

Roy Rodriguez 137 Jan 3, 2023
Floating Action Button But Moveable And Expandalbe

MeFab todo add the maven bacge here Floating Action Button but MOVEABLE and EXPA

Hussien Fahmy 6 Dec 30, 2022
➕ An efficient and beaufitul Multi Float action button library based on Twitter implemented in Jetpack Compose 🚀

Multi Float Action Button ➕ An efficient and beaufitul Multi Float action button library based on Twitter implemented in Jetpack Compose ?? Including

Geovani Amaral 8 Oct 15, 2022
Android Circular Progress Button

?? Before using this library, read information below ?? This library is not more supported. If you want to add new feature or fix a bug, grab source

Dmytro Danylyk 5.6k Jan 7, 2023
FButton - a flat button library for Android

FButton FButton is a custom Button of Android with "Flat UI" concept. FButton's design get inspiration from designmono. This library is very small and

Le Van Hoang 1.4k Dec 12, 2022
Android button which moves in eight direction.

Moving Button Android button which moves in eight direction. Preview Sample Demo You can download demo movie file here : demo.mov It's also on Youtube

Leonardo Taehwan Kim 130 Nov 22, 2022
[] Android floating action button

DEPRECATED Use the FloatingActionButton from the support library instead. FloatingActionButton Description Android floating action button which reacts

Oleksandr Melnykov 4k Jan 5, 2023
Floating Action Button for Android based on Material Design specification

FloatingActionButton Yet another library for drawing Material Design promoted actions. Features Support for normal 56dp and mini 40dp buttons. Customi

Zendesk 6.4k Dec 26, 2022
A simple Floating Action Button that shows an anchored Navigation View

Floating Navigation View A simple Floating Action Button that shows an anchored Navigation View and was inspired by Menu Material Fixed created by Tom

André Mion 1.3k Dec 29, 2022
A download button with pretty cool animation

ArrowDownloadButton A download button with pretty cool animation, this is an implemention of https://dribbble.com/shots/2012292-Download-Animation Enj

Rongchan Liu 966 Nov 29, 2022
Button which is visible while user holds it. Main use case is controlling audio recording state (like in Telegram, Viber, VK).

HoldingButton Button which is visible while user holds it. Main use case is controlling audio recording state (like in Telegram, Viber, VK). Getting s

Artem Hluhovskyi 594 Jan 1, 2023
[] An Android library for an expandable button menu

ExpandableButtonMenu ExpandableButtonMenu is an Android library which implements an expandable button that can be used as a substitute of a fixed size

Lemon Labs 325 Nov 14, 2022