Android self-defining switch (Switchbutton)

Source: Internet
Author: User

On a recent whim, I wrote a switch that defines the iphone as an imitation.

The students who need to be able to download. support Click on their own active scrolling, the rate can be changed according to their own needs. Touch scrolling, size yourself definition, support change style. Without recording the animation, we uploaded two pictures for you to see.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvahvhbmd5yw5iaw4xmjm=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/center "width=" "height=" 640 ">

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvahvhbmd5yw5iaw4xmjm=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/center "width=" "height=" 640 ">

Main code:

Package Com.example.switchbutton;import Android.annotation.suppresslint;import Android.content.context;import Android.content.res.resources;import Android.content.res.typedarray;import Android.graphics.canvas;import Android.graphics.paint;import Android.graphics.rectf;import Android.os.handler;import Android.util.AttributeSet; Import Android.view.motionevent;import Android.view.view;import Android.view.viewconfiguration;public class Switchbutton extends View {public static final int default_width = 100;public static final int default_heigth = 45;public static final int per_post_time = 20;public static final int CLICK = 0;public static final int left = 1;public static fina l int right = 2;private int mselectbg;private int munselectbg;private int mbordercolor;private int MSELECTCIRLCECOLOR;PRI vate int Munselectcirclecolor;private boolean ischecked;private Paint mpaint;private int mwidth;private int mHeight;  private int mclicktimeout; private int mtouchslop; Private float Manimmove;privatE final float VELOCITY = 350;private float firstdownx;private float firstdowny;private float lastdownx;private int mcricle postion;private int Mstartcriclepos;private int mendcirclepos;private boolean isscroll;private int status;private Handler mhander;private animrunnable manim;private Oncheckchangelistener Moncheckchangelistener;public interface Oncheckchangelistener {void OnCheck (Switchbutton switchbutton,boolean isChecked);} Public Switchbutton (context context, AttributeSet Attrs) {Super (context, attrs); Resources res = getresources (); int defaultselectbg = Res.getcolor (R.COLOR.DEFAULT_SWITCH_BUTTON_SELECT_BG); int DEFAULTUNSELECTBG = Res.getcolor (R.COLOR.DEFAULT_SWITCH_BUTTON_UNSELECT_BG); int defaultbordercolor = Res.getColor ( r.color.default_switch_button_border_color); int defaultselectcirclecolor = Res.getcolor (R.color.default_switch_ button_select_color); int defaultunselectcirclecolor = Res.getcolor (R.color.default_switch_button_unselect_color); TypedArray A = Context.obtainstyledattriButes (Attrs,r.styleable.switchbutton); MSELECTBG = A.getcolor (R.STYLEABLE.SWITCHBUTTON_SELECT_BG, DefaultSelectBg) ; MUNSELECTBG = A.getcolor (R.STYLEABLE.SWITCHBUTTON_UNSELECT_BG, DEFAULTUNSELECTBG); mbordercolor = A.getColor ( R.styleable.switchbutton_select_border_color, defaultbordercolor); mselectcirlcecolor = A.getColor ( R.styleable.switchbutton_select_cricle_color, defaultselectcirclecolor); munselectcirclecolor = A.getColor ( R.styleable.switchbutton_unselect_cricle_color, defaultunselectcirclecolor); isChecked = A.getboolean ( R.styleable.switchbutton_ischecked,false); a.recycle (); Initview (context);} private void Initview (context context) {Mpaint = new Paint (paint.anti_alias_flag); final float density = getresources (). GE  Tdisplaymetrics (). density; Manimmove = (int) (VELOCITY * density + 0.5f)/150; Own active scrolling speed mclicktimeout = viewconfiguration.getpressedstateduration () + viewconfiguration.gettapt  Imeout (); Click time Mtouchslop = Viewconfiguration.get (context). getscalEdtouchslop ();//touch scrolling slop Mhander = new Handler (); Manim = new animrunnable ();} @SuppressLint ("drawallocation") @Overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas); Mpaint.setcolor (Mbordercolor); Mpaint.setstyle (Paint.Style.STROKE); RECTF rect = new RECTF (0, 0, mwidth, mheight); Canvas.drawroundrect (rect, MHEIGHT/2, MHEIGHT/2, Mpaint); Mpaint.setcolor ( IsChecked?

MSELECTBG:MUNSELECTBG); RECTF innerrect = new RECTF (1, 1, mWidth-1, mHeight-1); Canvas.drawroundrect (Innerrect, MHEIGHT/2-1, MHEIGHT/2-1, Mpain t); Mpaint.setcolor (isChecked mselectcirlcecolor:munselectcirclecolor); Mpaint.setstyle (Paint.Style.FILL); Canvas.drawcircle (Mcriclepostion, MHEIGHT/2, MHEIGHT/2-1, mpaint);} @Overridepublic boolean ontouchevent (Motionevent event) {float x = Event.getx (); Float y = event.gety (); switch (Event.geta Ction ()) {case MotionEvent.ACTION_DOWN:if (Isscroll) {return false;} Firstdownx = X;firstdowny = Y;lastdownx = X;mcriclepostion = isChecked?

Mendcirclepos:mstartcriclepos;break;case MotionEvent.ACTION_MOVE:float Delax = X-lastdownx;setcriclepositon (Delax) ; lastdownx = X;invalidate (); break;case MotionEvent.ACTION_UP:float totalx = x-firstdownx;float totaly = y-firstdowny; Float time = Event.geteventtime ()-event.getdowntime (); if (Totalx < mtouchslop && totaly <mtouchslop && Amp Time < mclicktimeout) {status = Click;startautoscroll ();} Else{delax = X-lastdownx;setcriclepositon (delax); status = Mcriclepostion < MWIDTH/2? Left:right;startautoscroll ();} break;} return true;} Start your own initiative to scroll private void Startautoscroll () {isscroll = true;mhander.postdelayed (Manim, per_post_time);} Class Animrunnable implements runnable{@Overridepublic void Run () {mhander.postdelayed (this, per_post_time); Moveview ( );} Move private void Moveview () {if (status = = CLICK && isChecked) | | status = = left) {mcriclepostion-= manimmove;if (M Criclepostion < MHEIGHT/2) {mcriclepostion = Mheight/2;stopview (false);}} else if (STATus = = CLICK &&!ischecked) | | Status = = right) {mcriclepostion + = manimmove;if (Mcriclepostion > Mwidth-mheight/2) {mcriclepostion = Mwidth-mheight /2;stopview (True);}} Invalidate ();} Stop moving Viewprivate void Stopview (Boolean endchecked) {mhander.removecallbacks (manim); isscroll = false;ischecked = ENDCHECKED;//Callback Listener Event if (Moncheckchangelistener! = null) {Moncheckchangelistener.oncheck (Switchbutton.this, isChecked );}}} Set Center position private synchronized void Setcriclepositon (float delax) {int pos = (int) (mcriclepostion + Delax); if (Pos < Mhei GHT/2) {mcriclepostion = MHEIGHT/2;} else if (pos > MWIDTH-MHEIGHT/2) {mcriclepostion = MWIDTH-MHEIGHT/2;} Else{mcriclepostion = pos;}} @Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {int widthmode = Measurespec.getmode ( WIDTHMEASURESPEC); if (Widthmode = = Measurespec.unspecified | | widthmode = = measurespec.at_most) {mWidth = DEFAULT_WIDTH;} Else{mwidth = Measurespec.getsize (Widthmeasurespec);} int heightmode = MeAsurespec.getmode (HEIGHTMEASURESPEC); if (Heightmode = = Measurespec.unspecified | | heightmode = MeasureSpec.AT_MOST) { Mheight = Default_heigth;} Else{mheight = Measurespec.getsize (Heightmeasurespec);} Mstartcriclepos = Mheight/2;mendcirclepos = Mwidth-mheight/2;mcriclepostion = isChecked? Mendcirclepos:mstartcriclepos; Setmeasureddimension (Mwidth, mheight);} public Boolean isChecked () {return isChecked;} public void setchecked (Boolean isChecked) {this.ischecked = Ischecked;invalidate ();} public void Setoncheckchangelistener (Oncheckchangelistener oncheckchangelistener) {This.moncheckchangelistener = Oncheckchangelistener;}}

Attrs:

<?

XML version= "1.0" encoding= "Utf-8"?

> <resources> <declare-styleable name= "Switchbutton" > <attr name= "SELECT_BG" format= " Color "/> <attr name=" UNSELECT_BG "format=" color "/> <attr name=" Select_border_color "format=" Color "/> <attr name=" select_cricle_color "format=" color "/> <attr name=" Unselect_cricle_color " format= "Color"/> <attr name= "isChecked" format= "boolean" ></attr> </declare-styleable > </resources>


: http://download.csdn.net/detail/huangyanbin123/8173521

Android self-defining switch (Switchbutton)

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.