android--Slide Switch

Source: Internet
Author: User

One:

When turned on:

When closed:

Two: Steps:

1. Write a class slippingbtn inherit view and implement the Ontouchlistener interface. Overriding the parent class two constructors (one parameter, two arguments)

2. Initialize the background picture of the slider and record the position of the slide block when it is on and off, registering the Setontouchlistener event

When turned on:

Left coordinate of slide block: width of bg_on minus bg_slipping width
Slide block above coordinates: 0
The right coordinate of the slider: bg_on width
The coordinates below the slide block: the height of the bg_slipping
When closed:
Slider left coordinates: 0
Slide block above coordinates: 0
slider right coordinates: Gets the width of the slider
The coordinates below the slide block: the height of the bg_on
3. Initialize the status of the Switch settogglestate (Boolean status) and use a member variable currtogglestate to remember whether the current switch is turned on
4, set the listener, monitor the change of sliding switch status, respond to different events
5, the logic of the touch:

Case Motionevent.action_down:

Remember the current position; the slider is in the coasting State;

Break

Case Motionevent.action_move:

Update the position of the slider;

Break

Case MOTIONEVENT.ACTION_UP:

Slide block stationary;

Determine the position of the slider and the length of the bg_on: Record the switch status

Record the previous state, determine if this listener, and how to execute the listener,

Record the previous state as the current state;

Break

Invalidate () refresh the interface;

6, Onmeasure (): Measure the length and width of bg_on

7. Draw the switch on and off and the background of the slider

The specific code is as follows:

 Public classSlippingbtnextendsViewImplementsontouchlistener{PrivateBitmap bg_on,bg_off,bg_slipping; PrivateRect bg_on_location,bg_off_location; Private floatSlppcurlocation;//the slider when the money's in position    Private Booleanisslipping;//whether the slider is sliding    Private BooleanCurrtogglestate;//set the current state of the switch    Private BooleanIstogglestatuslistener;//whether to turn on the switch state monitoring    Private BooleanProtogglestate;//The status of the last switch, the default is false;    PrivateOntogglestatuslistener Listener;//Switch Listener         PublicHuadong (Context context) {Super(context);    Initview (); }         PublicHuadong (Context context, AttributeSet attrs) {Super(context, attrs);    Initview (); }        Private voidInitview () {bg_on=Bitmapfactory.decoderesource (Getresources (), r.drawable.on_btn); Bg_off=Bitmapfactory.decoderesource (Getresources (), r.drawable.off_btn); Bg_slipping=Bitmapfactory.decoderesource (Getresources (), r.drawable.white_btn); //coordinates of the slider when the switch is openBg_on_location =NewRect (Bg_on.getwidth ()-bg_slipping.getwidth (),0, Bg_on.getwidth (), Bg_on.getheight ()); //the coordinates of the slider when the switch is offBg_off_location =NewRect (0, 0, Bg_slipping.getwidth (), Bg_slipping.getheight ()); Setontouchlistener ( This); } @Override Public BooleanOnTouch (View V, motionevent event) {Switch(Event.getaction ()) { CaseMotionEvent.ACTION_DOWN:slppCurLocation=Event.getx (); Isslipping=true;  Break;  CaseMotionEvent.ACTION_MOVE:slppCurLocation=Event.getx ();  Break;  CaseMotionEvent.ACTION_UP:isSlipping=false; if(Slppcurlocation < Bg_on.getwidth ()/2) {currtogglestate=false; }Else{currtogglestate=true; }                        if(Istogglestatuslistener && Currtogglestate! =protogglestate) {Protogglestate= Currtogglestate;//Previous state This is only the current state;Listener.ontogglestatus (currtogglestate); }             Break; default:             Break;        } invalidate (); return true; } @Overrideprotected voidOnmeasure (intWidthmeasurespec,intHeightmeasurespec)    {setmeasureddimension (Bg_on.getwidth (), Bg_on.getheight ()); } @Overrideprotected voidOnDraw (canvas canvas) {Super. OnDraw (canvas); Matrix Matrix=NewMatrix (); Paint Paint=NewPaint (); if(currtogglestate) {//Open SwitchCanvas.drawbitmap (bg_on, Matrix, paint); }Else{//Switch offCanvas.drawbitmap (Bg_off, Matrix, paint); }        //H Draw Slider        floatLeft_slipp = 0;//the position of the slider        if(isslipping) {//slide in the stateLeft_slipp = Slppcurlocation-bg_slipping.getwidth ()/2; }Else{//Slider Stationary            if(currtogglestate) {Left_slipp= Bg_on.getwidth ()-bg_slipping.getwidth (); }Else{Left_slipp= 0; }        }                if(Left_slipp < 0) {Left_slipp= 0; }Else if(Left_slipp > (bg_on.getwidth)-bg_slipping.getwidth ())) {Left_slipp= Bg_on.getwidth ()-bg_slipping.getwidth (); } canvas.drawbitmap (Bg_slipping, Left_slipp,0, paint); }        //sets the status of the current switch on D     Public voidSettogglestate (Booleantogglestatus) {Currtogglestate=Togglestatus; }             Public Interfaceontogglestatuslistener{/*** Execution When switch status is changed *@paramtoggestate switching status after changing*/        voidOntogglestatus (Booleantoggestate); }    //Monitor the status of the slider     Public voidSetontogglestatuslistener (Ontogglestatuslistener listener) { This. Listener =Listener; Istogglestatuslistener=true; }}

XML file

    <com.view.util.SlippingBtn        android:id= "@+id/hd"        android:layout_width= "Wrap_ Content "        android:layout_height=" Wrap_content "/>

Activity invocation:

SLIPPINGBTN Toggle =(SLIPPINGBTN) Findviewbyid (R.ID.HD); Toggle.settogglestate (true); Toggle.setontogglestatuslistener (NewOntogglestatuslistener () {@Override Public voidOntogglestatus (Booleantoggestate) {                if(toggestate) {Toast.maketext (Getapplicationcontext (),"Open Switch", 1). Show (); }Else{Toast.maketext (Getapplicationcontext (),"Off Switch", 1). Show (); }                            }        });

android--Slide 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.