Custom Slide button Switch

Source: Internet
Author: User

Custom controls

 PackageTest.baway.com.mybutton.view;ImportAndroid.content.Context;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.graphics.Canvas;ImportAndroid.util.AttributeSet;Importandroid.view.MotionEvent;ImportAndroid.view.View;/*** Created by Gateway on 2016/6/21.*/ Public classMytogglebuttonextendsView {PrivateBitmap Bgpic; PrivateBitmap Iconpic; Private  floatToggleleft; Private  floatTogglemaxleft; Private Booleanisopen=false; Private  BooleanIshandsup =false; PrivateOntogglelistener Ontogglelistener;  PublicMytogglebutton (Context context) {Super(context); }     PublicMytogglebutton (Context context, AttributeSet attrs) {Super(context, attrs);    Init (attrs); }    Private voidInit (AttributeSet attrs) {//1. Get NamespacesString namespace = "Http://schemas.android.com/apk/res-auto"; //get the values we set from the custom properties        intBackgroundid = Attrs.getattributeresourcevalue (namespace, "Mybackground", 1); inticonID = Attrs.getattributeresourcevalue (namespace, "Myicon", 1); System.out.println ("Backgroundid---------" +backgroundid+ "------iconid----------" +iconID); BooleanTogglestate = Attrs.getattributebooleanvalue (namespace, "Mytoggle",false); if(Backgroundid! =-1 && iconID! =-1) {setbackgroundpic (Backgroundid, iconID);    } setState (Togglestate); }     PublicMytogglebutton (context context, AttributeSet attrs,intdefstyleattr) {        Super(context, attrs, defstyleattr);    Init (attrs); }    Private voidSetState (BooleanIsOpen) {Ishandsup=true; if(isOpen) {Toggleleft=Togglemaxleft; }Else{toggleleft=0; }    }    /*** Set slide switch background image *@parambgpic Background image *@paramiconpic Sliding Pictures*/     Public voidSetbackgroundpic (intBgpic,inticonpic) {         This. bgpic=Bitmapfactory.decoderesource (Getresources (), bgpic);  This. iconpic=Bitmapfactory.decoderesource (Getresources (), iconpic); Togglemaxleft= This. Bgpic.getwidth ()- This. Iconpic.getwidth (); } @Overrideprotected voidOnLayout (BooleanChangedintLeftintTopintRightintbottom) {        Super. OnLayout (changed, left, top, right, bottom); } @Overrideprotected voidOnmeasure (intWidthmeasurespec,intHeightmeasurespec) {//super.onmeasure (Widthmeasurespec, heightmeasurespec);setmeasureddimension (Bgpic.getwidth (), Bgpic.getheight ()); } @Overrideprotected voidOnDraw (canvas canvas) {canvas.drawbitmap (Bgpic,0,0,NULL); //No, let's slide out the left .        if(toggleleft<0) {Toggleleft=0; }        //Why don't you slide the right        if(toggleleft>togglemaxleft) {Toggleleft=Togglemaxleft; } IsOpen= Toggleleft>0; if(ishandsup) {if(ontogglelistener!=NULL) {ontogglelistener.ontoggle (IsOpen); } ishandsup=false; } canvas.drawbitmap (Iconpic,toggleleft,0,NULL); Super. OnDraw (canvas); } @Override Public Booleanontouchevent (Motionevent event) {Switch(Event.getaction ()) { CaseMotionEvent.ACTION_DOWN:toggleLeft=event.getx ()-iconpic.getwidth ()/2;  Break;  CaseMotionEvent.ACTION_MOVE:toggleLeft=event.getx ()-iconpic.getwidth ()/2;  Break;  CaseMotionEvent.ACTION_UP:isHandsUp=true; if(Event.getx () >bgpic.getwidth ()/2) {Toggleleft=Togglemaxleft; }Else{toggleleft=0; }                 Break;        } invalidate (); return true; }     Public voidSetontogglelistener (Ontogglelistener ontogglelistener) { This. ontogglelistener=Ontogglelistener; }     Public Interfaceontogglelistener{voidOntoggle (BooleanIsOpen); }}

Way One:

Set the background and slide buttons in set mode

In the layout

<Test.baway.com.mybutton.view.MyToggleButton        android:layout_width= "Wrap_content"         android:layout_height= "Wrap_content"        android:id= "@+id/btn"/>



In activity

Mytogglebutton BTN =(Mytogglebutton) Findviewbyid (R.ID.BTN);
Set the background and slide button btn.setbackgroundpic (r.mipmap.slide_background2,r.mipmap.slide_icon2); Btn.setontogglelistener (NewMytogglebutton.ontogglelistener () {@Override Public voidOntoggle (BooleanIsOpen) { if(IsOpen) {toast.maketext (mainactivity. This, "Open", Toast.length_short). Show (); }Else{toast.maketext (mainactivity). This, "Close", Toast.length_short). Show (); } } });

Way two:

Set the background and slide buttons by customizing the properties

Create Attrs.xml in values
<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "Mytogglebutton" >        <attr name= "Mybackground" format= "reference" ></attr>        <attr name= "Myicon" format= "reference "></attr>        <attr name=" Mytoggle "format=" boolean "></attr>    </declare-styleable> </resources>

In the layout

Add a Namespace

As: xmlns:app= "Http://schemas.android.com/apk/res-auto" (change Res-auto to package name in Eclipse)
<Test.baway.com.mybutton.view.MyToggleButton        app:mybackground= "@mipmap/slide_background"         App:myicon= "@mipmap/slide_icon"        app:mytoggle= "true"        android:layout_width= " Wrap_content "        android:layout_height=" Wrap_content "        android:id=" @+id/btn "/>

In activity

Mytogglebutton BTN =(Mytogglebutton) Findviewbyid (R.ID.BTN); Btn.setontogglelistener (NewMytogglebutton.ontogglelistener () {@Override Public voidOntoggle (BooleanIsOpen) {                if(IsOpen) {toast.maketext (mainactivity. This, "Open", Toast.length_short). Show (); }Else{toast.maketext (mainactivity). This, "Close", Toast.length_short). Show (); }            }        });

Custom Slide button Switch

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.