2. Implement the following code
Public classMainactivityextendsappcompatactivity {TextView tx1, tx2; Switch SW; ToggleButton TB; intA, B; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); TX1=(TextView) Findviewbyid (R.id.textview); TX2=(TextView) Findviewbyid (R.ID.TEXTVIEW2); SW=(Switch) Findviewbyid (R.ID.SWITCH1); TB=(ToggleButton) Findviewbyid (R.id.togglebutton); Sw.settext ("Sesame Gate"); Sw.settextcolor (color.red); Sw.setonclicklistener (Linstener1); Tb.settext ("Switch 2"); Tb.settextcolor (Color.green); Tb.setonclicklistener (LINSTENER2); A= 1; b= 1; } //Listener 1 things to doSwitch.onclicklistener Linstener1=NewSwitch.onclicklistener () { Public voidOnClick (View v) {if(A = = 1) {Tx1.settext ("Open Sesame"); Tx1.settextcolor (Color.green); A++; } Else{Tx1.settext ("The door is closed."); Tx1.settextcolor (Color.Black); A=1; } } }; //Listener 2 things to doTogglebutton.onclicklistener Linstener2 =NewTogglebutton.onclicklistener () { Public voidOnClick (View v) {if(b==1) {Tx2.settext (The lights are on.); Tx2.settextcolor (color.red); b++; } Else{Tx2.settext ("The lights are off."); Tx2.settextcolor (Color.Black); b=1; } } };}
Run effect
Use of switch and ToggleButton