Android switch button example

A switch is type of button that can only have two states ON and OFF. You can set the initial state and then the user can change it. To get the current state you can check if the switch is checked or not, in addition to that you can attach a OnCheckedChangeListener to the switch to get notification when the state changes.

Android switch button OFF state Android switch button ON state

Android Screen Layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" 
    android:padding="5dp">

    <Switch
        android:id="@+id/mySwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp"
        android:text="Play with the Switch" />

    <TextView
        android:id="@+id/switchStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/mySwitch"
        android:layout_marginTop="22dp"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    
</RelativeLayout>

Android Main Activity

package com.as400samplecode;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.TextView;

public class MainActivity extends Activity {

 private TextView switchStatus;
 private Switch mySwitch;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  switchStatus = (TextView) findViewById(R.id.switchStatus);
  mySwitch = (Switch) findViewById(R.id.mySwitch);

  //set the switch to ON 
  mySwitch.setChecked(true);
  //attach a listener to check for changes in state
  mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

   @Override
   public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {

    if(isChecked){
     switchStatus.setText("Switch is currently ON");
    }else{
     switchStatus.setText("Switch is currently OFF");
    }

   }
  });
  
  //check the current state before we display the screen
  if(mySwitch.isChecked()){
   switchStatus.setText("Switch is currently ON");
  }
  else {
   switchStatus.setText("Switch is currently OFF");
  }
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

Reference


158 comments :

  1. Replies
    1. Thanks for providing coding about Android switch button, which is only sustained in android 4.0 and greater device. It’s really helpful for my students, who are looking for IT related writing services at http://www.essaywriter.org.uk/. I would like to share this example with our creative students and professional teacher. I am sure this post is helpful for them.

      Delete
    2. Android switch button is a different kind of toggle button that’s mainly used as Android 4.0. Switch offers a slider controller. Equally Switch and ToggleButton are CompoundButton’s subclasses. Here you are sharing perfect coding using all class and subclasses which is useful for IT field students, who are taking university assignment help service from the expert at Assignment Help Folks consultancy. I found such kind of useful and informative post. Many thanks for sharing here, still waiting for new post.

      Delete
  2. Great work. works very nicely. Thanx..

    ReplyDelete
  3. mySwitch.setChecked(true); // I am getting a NullPointerException

    ReplyDelete
    Replies
    1. look at XML name of Switch and .java name at line 22

      Delete
  4. Replies
    1. yes, we can...



      Delete
    2. :) and we probably should do it in our Screen Layout xml file

      Delete
  5. I love the President of the outcome fifa 14 coins on the case now, each of us the other half has become a part of life. We are dependent fifa 14 coins the new home for our efforts.

    ReplyDelete
    Replies
    1. You always can publish something absorbing that does not waste minutes of your life like what youproessaywriting.com essay writing service see on countless other sites. This is very interesting and I will be back for more. Thanks for sharing

      Delete
  6. How I can do some action only if user change the state of switch, not by setting the state pragmatically??

    ReplyDelete
  7. Ty for the code. Any ideal how to implement an mysql database update. For example: if switch is "on" write "1" and if switch is "off" write"0" to database row "xy" where id = id.

    Many thanks in advance

    ReplyDelete
  8. Nice job :) Thank you

    ReplyDelete
  9. It's great... Thanks a lot.

    ReplyDelete
  10. how to use 2 switchs

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Thank you very much! It is so useful information. I also think that nowadays it is so hard to find a good doctor who will be a specialist in his area. I know that college essay topics writing service is hard to find also. Just think about it.

    ReplyDelete
  14. i switch to "off" then i go to other class, but when i go back to the main screen. Switch is in "on". whenever i "off" the switch, its always going back to "on". when i go to other class.
    how to fix it?

    ReplyDelete
    Replies
    1. You need to implement the method in onResume()

      Delete
  15. Very efficiently written information. It will be valuable to everyone who uses it, including myself. Thanks a lot!
    Accounting Project Help
    Investment Centers Accounting Homework Help

    ReplyDelete
  16. Assignment Help
    The key is to give the peruser a little look into your experience, which urges them to need to take in more by perusing your resume

    ReplyDelete
  17. Quality Content Writing Services
    SpinRewriter Manual Article Spinning Service Reviews
    Really i appreciate the effort you made to share the knowledge. This is really a great stuff for sharing. Keep it up . Thanks for sharing.

    ReplyDelete
  18. Had to cut it short. Sounds like you woke her up. Lol Fifa 15 key

    ReplyDelete
  19. thank you very much...
    people like you are the soul of the good thins that happen
    regards sarat

    ReplyDelete
  20. Wow, I have to say. Wow, how come nobody came across your post before. I have always been wondering what else can REST service do and you have just answered that.
    Hungry Shark Evolution Hack Cheats Apk

    ReplyDelete
  21. What a great information you shared with us, I am inspired by the method for the stage. It kept joined me regularly. Keep doing awesome. Thanks for sharing this blog article.
    Assignment Help

    ReplyDelete
  22. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. . https://www.allassignmenthelp.com.au

    ReplyDelete
  23. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. . buy specs online

    ReplyDelete
  24. Thanks for your code. but how can i change the caption to right side of switch??

    ReplyDelete
  25. Amaze! I have been looking bing for hours because of this and i also in the end think it is in this article! Maybe I recommend you something helps me all the time? Here's it

    ReplyDelete
  26. Great. This article is excellent. I have read many articles with this topic, but I have not liked. I think I have the same opinion with you.

    ReplyDelete
  27. Wow, wonderful blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is fantastic, let alone the content!

    ReplyDelete
  28. I always love reading your blog...I’ve bookmarked it so that I can come back and read it again and again. Once is not enough to process so much valuable information.

    ReplyDelete
  29. Thank you for sharing valuable information. Nice post. I enjoyed reading this post.
    - Mortal Kombat XL
    - Atari Breakout
    - Dragon Ball Z Games

    ReplyDelete
  30. The Market Share of Android Is Attracting Mobile App Developers buy argumentative essay Choosing the Android Platform To Build Mobile Apps For Your Business

    ReplyDelete
  31. I know that it's a noob question but I'm new into this. How can I store the switch settings? I i switch to on and close the app, when a open it again it's ofdoff

    ReplyDelete
  32. Boost Your Business Prospects With Custom Android Application Development Computer Science Assignment Help Best Anti Virus Software For Your Android And iPhone Device

    ReplyDelete
  33. Best Anti Virus Software For Your Android And iPhone Device Research Proposal Writing Service Amazing Android Free Apps: ElectroDroid All Your Electronics Needs at Hand

    ReplyDelete
  34. Let’s keep out sites for your child! click:
    brain games | puzzle games | tetris | happy wheels | agario | abcya | fnaf 4 | super mario games
    To play for free!

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. Get the best assignment help service from leading assignment help service provider in UK, USA, and Australia- www.makemyassignments.com

    ReplyDelete
  37. that's a more interesting and informative stuff, i like this article.

    Jalandhar Call Girls

    Kalka Ji Call Girls

    ReplyDelete
  38. All the best blogs that is very useful for keeping me share the ideas
    of the future as well this is really what I was looking for, and I am
    very happy to come here. Thank you very much
    earn to die
    earn to die 2
    earn to die 3
    Hi! I’ve been reading your blog for a while now and finally got the
    earn to die 4
    courage to go ahead and give youu a shout out from
    earn to die 6
    Austin Texas! Just wanted to tell
    earn to die 5
    Hi! I’ve been reading your blog for a while now and finally got the
    happy wheels
    strike force heroes
    slitherio
    you keep up the fantastic work!my weblog
    age of war
    earn to die 5
    good game empire

    ReplyDelete
  39. Are these real comments?

    There is a new update:
    switch_general.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    ...

    ReplyDelete
  40. nice article i like your blog thanka for sharing this info .


    jaipur Escorts

    Dehradun Escorts

    ReplyDelete
  41. Great! Thanks for sharing the information. That is very helpful for increasing my knowledge in this fiel
    Red Ball | | duck life | Slitherio
    Red Ball 2 | Red Ball 3 | Red Ball 4

    ReplyDelete
  42. I was examining consistently this website that i'm empowered! Very useful facts particularly the last cycle :) I personally deal with similarly info a great deal. I was trying to find that information for a long time. clash of clans hack

    ReplyDelete
  43. Howdy, I stumbled upon your web site by means of Search engines while seeking a identical topic, your website developed, seems like wonderful. We have added onto favourites features in my own bookmarks. clash of clans hack

    ReplyDelete
  44. obviously just like your internet site nevertheless you need to analyze the transliteration on some of your content regularly. Some are usually filled using punctuation issues and I locating that pretty troublesome to tell the truth alternatively I will unquestionably return once more. clash of clans generator

    ReplyDelete
  45. I just wanna know that...how do we change the initial state of switch button...thatk is when i launch the main activity the swtich button should in on state...looking forward to your reply...thaknx in advance :)

    ReplyDelete

  46. Hotmail is an email account of Microsoft Corporation. Like Google's Gmail, it is full of features usually xuyen.Neu of an email you want to register an account please follow these basic steps:
    Hotmail login

    Hotmail review

    Sign in to hotmail

    Login to hotmail

    Recover hotmail password

    Tank Trouble is a very interesting flash game about tanks, about war and about destruction
    TANK TROUBLE | TANK TROUBLE 2

    One Penguin Takes it personally when he is surfing the web and stumbles upon a web site telling him that he cant fly, after that he sets his mind to research and practice flying until he can prove the world that he can..
    IO GAMES | Slitherio | LEARN TO FLY | LEARN TO FLY 2

    Strike Force Heroes is a new game action-packed shooter from the creators of Raze; with 3 game modes, 15 campaign missions and over 65 weapons.
    Strike Force Heroes 4

    Strike Force Heroes


    ReplyDelete
  47. This comment has been removed by the author.

    ReplyDelete
  48. I want to change the state from Unchecked to checked at 2 P.M. everyDay..
    How to do that?

    ReplyDelete
  49. I want to change the state from Unchecked to checked at 2 P.M. everyDay..
    How to do that?

    ReplyDelete
  50. I was examining consistently this website that i'm empowered! Very useful facts particularly the last cycle
    Richest Actors Of Game of Thrones
    Clash of Clans Mode APK

    ReplyDelete
  51. My friend proposed I will this way blog site. He or she had been entirely correct. This send actually created my time. You can't take into account just how a lot time I had created invested with this details! Thank you so much! .clash of clans hack

    ReplyDelete
  52. I am sure that the informative you shared througheful for my future. keep sharing. A good blog.
    tank trouble 2 | run 2

    ReplyDelete
  53. This is a superb post here. I am agree with your opinion I have read your article is really very helpful and informative for me. Thanks for sharing. Keep it up.
    Rubber Matting for sale

    ReplyDelete
  54. A great possibility for me and it was a superb knowledge to view this site. Very difficult to uncover these beneficial web page or web site. I have many devices and achieving proper picture of these worked well and energy continues to be seeing about this weblog. Often my own intend to make my personal site as well as my own enjoyment is growing due to this page. I we do hope you may well be more effective.
    list of emoticons | www google search | facebook lite

    ReplyDelete
  55. this is one of the cult game now, a lot of people enjoy playing them . Also you can refer to the game :
    age of war | red ball | earn to die 5 | Tank trouble | happy wheels | earn to die 6
    The game controls are shown just under . Movement mechanisms primarily include acceleration and tilting controls.
    tank trouble unblocked | wings io | strike force heroes | age of war | hotmail login

    ReplyDelete
  56. Such a nice explanation. Thanks :)

    ReplyDelete
  57. Awesome blog..really interesting which grabbed my attention....thanks for sharing......keep posting.......
    Cost Accounting Assignment Help |

    ReplyDelete
  58. This blog post really grabbed my attention....thanks for sharing............keep posting.......
    UOP Assignment help |

    ReplyDelete
  59. keep sharing….. Awesome article which really grabbed my attention…keep posting……
    Homework Help

    ReplyDelete
  60. it doesn't work with an slide switch.

    Errors, errors everywhere!

    ReplyDelete
  61. Missing ")"
    line:
    mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    ReplyDelete
  62. Great article :) thanks for sharing it.

    i have also found good android tutorial link.

    http://blog.nkdroidsolutions.com/android-switchcompat-example-tutorial/

    ReplyDelete

  63. Thanks for the great post Friv.Com, Friv.Com! I quite enjoyed reading it Kizi 6000, Kizi 7000 you can be a great author. Kizi 8000, Kizi 9000 I will remember to bookmark your blog and definitely will come back later Kizi 360, Kizi.Com. I want to encourage continue your great job Yepi 300, Yepi 5, have a nice day Yepi 600, Yepi 9000!

    ReplyDelete
  64. Thank you for your guidance so sweet Yepi.Com, Friv 9 all this time later in Friv 8, Friv 7, I have found it Friv 6, Friv 100 and loved the final result Friv 6000, Friv 7000. I appreciate time you spend sharing your skills on Friv 8000,Friv 9000, Yepi Games !

    ReplyDelete
  65. Inflate the menu? what is supposed to do?

    ReplyDelete
  66. Beats Studio Wireless Over-Ear Headphone Review writing service and Beats Studio Wireless Over-Ear Headphone Review writing Help Beats Studio Wireless Over-Ear Headphone Review These headphones are by far the most costly earphones I have actually ever bought.
    Beats Studio Wireless Over-Ear Headphone Review

    ReplyDelete
  67. This is really a great stuff for sharing. Thanks for sharing.
    economics help online

    ReplyDelete
  68. thanks very much for sharing useful information........
    Assignment Help

    ReplyDelete
  69. Oh my goodness! an amazing article dude. Thank you However I am experiencing issue with ur rss cara mengobati osteoarthritis. Don’t know why Unable to subscribe to it. Is there anyone getting identical rss problem? Anyone who knows kindly respond. Thnkx obat radang paru-paru

    ReplyDelete
  70. It’s a very deterministic opportunity until perusal this one you power be musing about sentimental hubbub which goes care of you when you requirement any late night show and can’t monitoring your sentimental of not beget those hot bodies. Gurgaon Escorts

    ReplyDelete
  71. Thank you for sharing. Your blog posts are more interesting and impressive. I think there are many people like and visit it regularly, including me. cheapest locksmith las vegas

    ReplyDelete
  72. This is one of the cult game now, a lot of people enjoy playing them . Also you can refer to the game :
    gold mine strike | pokemon go 2
    The game controls are shown just under . Movement mechanisms primarily include acceleration and tilting controls.
    stickman games | stick war 2 | animal jam 2

    ReplyDelete
  73. First of all i am saying that i like your post very much.I am really impressed by the way in which you presented the content and also the structure of the post. Hope you can gave us more posts like this and i really appreciate your hardwork.

    Happy New Year 2018
    valentine week list
    valentine week list 2017

    ReplyDelete
  74. Nice blog and absolutely outstanding. You can do something much better but i still say this perfect.Keep trying for the best.
    human instagram followers

    ReplyDelete
  75. Nice knowledge gaining article. This post is really the best on this valuable topic.
    buy real instagram followers

    ReplyDelete
  76. Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog.
    buy real active instagram followers

    ReplyDelete
  77. This is a great article thanks for sharing this informative information. I will visit your blog regularly for some latest post. I will visit your blog regularly for Some latest post.
    Dyson V8 vs V6

    ReplyDelete
  78. Really impressive post. I read it whole and going to share it with my social circules. I enjoyed your article and planning to rewrite it on my own blog.
    ldyson v8 absolute vs v6

    ReplyDelete
  79. Great Article it its really informative and innovative keep us posted with new updates. its was really valuable. thanks a lot.
    Reputation Management

    ReplyDelete
  80. I’ve been searching for some decent stuff on the subject and haven't had any luck up until this point, You just got a new biggest fan!..
    Chester Taxi Service

    ReplyDelete
  81. Nice blog and absolutely outstanding. You can do something much better but i still say this perfect.Keep trying for the best.
    Wedding Planning

    ReplyDelete
  82. You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant!
    Chester Taxi Service

    ReplyDelete
  83. I’ve read some good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to create such a great informative website.
    Davika hone intragram

    ReplyDelete
  84. This is a great article thanks for sharing this informative information. I will visit your blog regularly for some latest post. I will visit your blog regularly for Some latest post.
    bowls second hand

    ReplyDelete
  85. Excellent website you have here, so much cool information!..
    Hairless Cats

    ReplyDelete
  86. Thank you for helping people get the information they need. Great stuff as usual. Keep up the great work!!!
    alopecia areata

    ReplyDelete
  87. The website is looking bit flashy and it catches the visitors eyes. Design is pretty simple and a good user friendly interface.
    2017 hair trends men

    ReplyDelete
  88. All the best blogs that is very useful for keeping me share the ideas of the future as well this is really what I was looking for, and I am
    very happy to come here. Thank you very much
    animal jam codes | five nights at freddy's 4 | hotmail login

    ReplyDelete

  89. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work.
    hotmail login | red ball

    ReplyDelete