"Android" Custom controls implement sliding switches (switch)

Source: Internet
Author: User

~ Reprint Please indicate source: http://blog.csdn.net/u013015161/article/details/46704745

Introduced

Last night wrote an android slide switch, ie Slideswitch. The effect is as follows:

Realize

The implementation of the idea is very simple, monitoring the touch event on the control, and constantly refreshed, so that the slider in the position of the finger to draw, the slider to follow the finger slide display effect.
Check the code First:
Slideswitch.java

 PackageCom.example.slideswitchexample;ImportAndroid.content.Context;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Color;ImportAndroid.graphics.Paint;ImportAndroid.util.AttributeSet;ImportAndroid.view.MotionEvent;ImportAndroid.view.View; Public  class slideswitch extends View{    PrivatePaint Mpaint =NewPaint (Paint.anti_alias_flag);//anti-aliasing    BooleanIsOn =false;floatCurX =0;floatCenterY;//y Fixed    floatViewwidth;floatRadiusfloatLinestart;//The position at which the line segment begins (horizontal axis, i.e.    floatLineend;//position where the line segment ends (ordinate    floatLineWidth;Final intScale =4;//Control length is a multiple of the radius of the sliding circleOnstatechangedlistener Onstatechangedlistener; Public Slideswitch(context context, AttributeSet attrs,intDefstyle) {Super(Context, attrs, Defstyle); } Public Slideswitch(context context, AttributeSet attrs) {Super(context, attrs); } Public Slideswitch(Context context) {Super(context); }@Override     Public Boolean ontouchevent(Motionevent event) {//TODO auto-generated method stubCurX = Event.getx ();if(event.getaction () = = motionevent.action_up) {if(CurX > Viewwidth/2) {CurX = Lineend;if(false= = IsOn) {The callback function is called only if the state has changed.Onstatechangedlistener.onstatechanged (true); IsOn =true; }            }Else{CurX = Linestart;if(true= = IsOn) {onstatechangedlistener.onstatechanged (false); IsOn =false; }            }        }/ * Call ondraw*/via refresh         This. Postinvalidate ();return true; }@Override    protected void onmeasure(intWidthmeasurespec,intHEIGHTMEASURESPEC) {//TODO auto-generated method stub        Super. Onmeasure (Widthmeasurespec, Heightmeasurespec);/ * Keep wide is high scale/2 times, that is, the diameter of the circle * /         This. Setmeasureddimension ( This. Getmeasuredwidth (), This. Getmeasuredwidth () *2/scale); Viewwidth = This. Getmeasuredwidth ();        radius = Viewwidth/scale; LineWidth = Radius *2F//Line width equals slider diameterCurX = radius; CenterY = This. Getmeasuredwidth ()/scale;//centery is half the heightLinestart = radius; Lineend = (Scale-1) * RADIUS; }@Override    protected void OnDraw(Canvas canvas) {//TODO auto-generated method stub        Super. OnDraw (canvas);/ * Limit sliding range * /CurX = CurX > Lineend?lineend:curx; CurX = CurX < Linestart?linestart:curx;/ * Dash * /Mpaint.setstyle (Paint.Style.STROKE); Mpaint.setstrokewidth (linewidth);/ * Line in left part, Blue * /Mpaint.setcolor (Color.Blue); Canvas.drawline (Linestart, CenterY, CurX, CenterY, Mpaint);/ * Line in the right part, Grey * /Mpaint.setcolor (Color.gray); Canvas.drawline (CurX, CenterY, Lineend, CenterY, Mpaint);/ * Draw Circle * /        /* Draw the leftmost and most right circle, the diameter of the straight segment width, that is, in the straight segment with a semicircle on each side .Mpaint.setstyle (Paint.Style.FILL);        Mpaint.setcolor (Color.gray); Canvas.drawcircle (Lineend, centery, LineWidth/2, Mpaint);        Mpaint.setcolor (Color.Blue); Canvas.drawcircle (Linestart, centery, LineWidth/2, Mpaint);/ * Circular slider * /Mpaint.setcolor (Color.ltgray);    Canvas.drawcircle (CurX, CenterY, radius, mpaint); }/ * Set switch status change listener * /     Public void Setonstatechangedlistener(Onstatechangedlistener o) { This. Onstatechangedlistener = O; }/ * Internal interface, switch status change listener * /     Public  interface onstatechangedlistener {         Public void onstatechanged(BooleanState); }}

The comments should be very detailed. The main points are as follows.
1. Override the Onmeasure method to make the control highly dependent on the width of the control . This ensures that the control's aspect ratio is always guaranteed, regardless of how it is set in the layout file.
2, control the movement of the slider block range
3, defines the internal interface Onstatechangedlistener, and in the custom control defines its object and the method Setonstatechangedlistener from the external assignment, in order to listen to the switch state change event and invoke the callback .

Use and Demo

Add the control in the layout file to use. The demo effect is animated (the color in the demo is green and the animation is blue because the green will cause problems when capturing gif, temporarily changing).
The layout file in the demo is as follows:
Activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <com.example.slideswitchexample.SlideSwitch        android:id="@+id/slide_switch"        android:layout_width="200dp"        android:layout_height="wrap_content"        android:layout_centerInParent="true"/></RelativeLayout>

The activity code in the demo is as follows:
Mainactivity.java

 PackageCom.example.slideswitchexample;ImportCom.example.slideswitchexample.SlideSwitch.OnStateChangedListener;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.widget.Toast; Public  class mainactivity extends Activity {Slideswitch Sswitch;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Sswitch = (slideswitch) This. Findviewbyid (R.id.slide_switch); Sswitch.setonstatechangedlistener (NewOnstatechangedlistener () {@Override             Public void onstatechanged(BooleanState) {//TODO auto-generated method stub                if(true= = State) {Toast.maketext (mainactivity. This,"switch is turned on", +). Show (); }Else{Toast.maketext (mainactivity). This,"switch is off", +). Show ();    }            }        }); }}

Click here to download Demo Project

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android" Custom controls implement sliding switches (switch)

Related Article

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.