Android's implementation slide switch assembly

Source: Internet
Author: User

Since Android does not provide components such as sliding switches, we need to implement a custom view component to achieve the sliding switch effect.

Here is a sample code that consists of three classes: Switch component view, State listener interface, mainactivity

Let's take a look at the entire demo:


Let's take a look at the complete code for the view component, which has been commented:

Package Com.bear.swtichbuttondemo;import Java.util.arraylist;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.graphics.matrix;import Android.graphics.paint;import Android.graphics.rect;import Android.util.attributeset;import Android.view.motionevent;import Android.view.view;import android.view.view.ontouchlistener;/** * Custom slide Switch */public class Myswitchbutton extends view implements Ontouchlistener { Private Bitmap switchonbkg; The background of the switch is private Bitmap switchoffbkg; Switch off when the background private Bitmap Slipswitchbutton; Slide Switch Picture Private Boolean isslipping = false; Whether you are sliding private Boolean Isswitchon = false; The status of the current switch, true to open, flase to close the private float previousx; The horizontal coordinates of the finger when pressed xprivate float CurrentX; The current horizontal coordinate xprivate arraylist<onswitchlistener> onswitchlistenerlist; Switch Listener List public Myswitchbutton (context context, AttributeSet Attrs) {Super (context, attrs); init ();} private void Init () {This.setontOuchlistener (this); Set Touch Listener onswitchlistenerlist = new arraylist<onswitchlistener> ();} public void Setimageresource (int switchbkg, int slipbtn) {switchonbkg = Bitmapfactory.decoderesource (this.getresources (), switchbkg); switchoffbkg = Bitmapfactory.decoderesource (This.getresources (), switchbkg); SlipSwitchButton = Bitmapfactory.decoderesource (This.getresources (), slipbtn);} public void Setswitchstate (Boolean switchState) {This.isswitchon = Switchstate;this.invalidate ();} public Boolean getswitchstate () {return this.isswitchon;} public void Setonswitchstatelistener (Onswitchlistener listener) {Onswitchlistenerlist.add (listener);} @Overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas); Matrix matrix = new Matrix (); Paint paint = new paint (); float leftslipbtnx; Slide the left coordinate of the button//draw the background picture of the switch Canvas.drawbitmap (switchonbkg, Matrix, paint); if (isslipping) {//If you are sliding if (CurrentX > Switchonbkg.getwidth ()) {leftslipbtnx = Switchonbkg.getwidth ()-Slipswitchbutton.getwidth ();} else {LeftSlipBtnX = Currentx-slipswitchbutton.getwidth ();}} else {//If there is no sliding if (Isswitchon) {leftslipbtnx = Switchonbkg.getwidth ()-Slipswitchbutton.getwidth ();} else {leftslipbtnx = 0;}} If the finger slides out of the range of the switch, this should be handled if (Leftslipbtnx < 0) {leftslipbtnx = 0;} else if (Leftslipbtnx > Switchonbkg.getwidth ()-Slips Witchbutton.getwidth ()) {leftslipbtnx = Switchonbkg.getwidth ()-Slipswitchbutton.getwidth ();} Draw the switch picture on the canvas Canvas.drawbitmap (Slipswitchbutton, leftslipbtnx, 0, paint);} @Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec, HEIGHTMEASURESPEC); Setmeasureddimension (Switchonbkg.getwidth (), Switchonbkg.getheight ());} @Overridepublic boolean OnTouch (View V, motionevent event) {//Get Touch action type int action = event.getaction (); switch (action) {CAs e motionevent.action_move://If the finger is now in a moving state CurrentX = Event.getx (); Break;case motionevent.action_down:// If now the finger just pressed on the screen state isslipping = True;break;case motionevent.action_up://If now the finger just left the screen state isslipping = False;boolean PreviouSstate = Isswitchon;if (Event.getx () > (Switchonbkg.getwidth ()/2)) {Isswitchon = true;} else {Isswitchon = false;} Call the interface callback method to notify the listener if (previousstate! = Isswitchon) {if (onswitchlistenerlist.size () > 0) {for (Onswitchlistener Listener:onswitchlistenerlist) {listener.onswitched (Isswitchon);}}} Break;default:break;} This.invalidate (); return true;}}

Let's take a look at the Switch status monitoring interface code, as follows:

Package Com.bear.swtichbuttondemo;public interface Onswitchlistener {public abstract void onswitched (Boolean Isswitchon);}

Finally, the code in our activity, here need to pass two images to the custom components, of course you can also pass two of their own good pictures, the code is as follows:

Package Com.bear.swtichbuttondemo;import Android.app.activity;import Android.os.bundle;import Android.view.View; Import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.toast;public class Mainactivity extends Activity {private Myswitchbutton myswitchbutton;private Button mybtn; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Setupviews ();} private void Setupviews () {Myswitchbutton = (Myswitchbutton) Findviewbyid (R.id.my_switch_button);// Pass the picture to the custom component Myswitchbutton.setimageresource (r.drawable.switch_bkg_switch,r.drawable.switch_btn_slip); myBtn = ( Button) Findviewbyid (R.id.button);//Set Switch status Monitor Myswitchbutton.setonswitchstatelistener (new Onswitchlistener () {@ Overridepublic void Onswitched (Boolean Isswitchon) {if (Isswitchon) {Toast.maketext (Mainactivity.this, "Toggle on", Toast.length_short). Show ();} else {toast.maketext (mainactivity.this, "switch Off", Toast.length_short). Show ();}}); Mybtn. Setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {Boolean isOn = Myswitchbutton.getswitchstate (); myswitchbutton.setswitchstate (!ison);}});}

Finally, attach the code:

Android's implementation slide switch assembly

Android's implementation slide switch assembly

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.