Recently in Android project to use the switch control, but android in the self-contained switch control is not satisfied, so it is intended to write a switch control through a custom view
The switch control of iOS is, of course, the target I want to emulate.
First:
Analysis:
The switch control contains two parts, one is a circle, the other is a rounded rectangle, so we just need to draw these two parts by view.
Directly on the code:
Package Com.example.widget;import Com.example.switchbutton_master. R;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.RectF ; Import Android.util.attributeset;import Android.util.log;import android.view.motionevent;import Android.view.View ; Import android.widget.toast;//Custom Switch control public class Switchbuttonview extends view{//switch Circle button private Bitmap Swithsilder ;//Gets the width of the switch circle private int swithwidth;//Switch circle position on the x-axis private int swithshilerx;//in a slightly resized length private int baseheight;private int basewidth;//The current state of the switch control, true: On, false: Off private Boolean currentstate = false;//brush private paint paint; /** Switch Status change monitor */private Ontogglestatechangelistener Mlistener; Public Switchbuttonview (context context, AttributeSet Attrs) {Super (context, attrs); Initbitmap (); } private void Initbitmap () {Swithsilder = Bitmapfactory.decoderesouRce (Getresources (), r.drawable.swich_slider_new); Swithwidth = Swithsilder.getwidth (); baseheight = Swithwidth/10;basewidth = Swithwidth/5;paint = new Paint (); The style of the initial brush does not fill paint.setstyle (Paint.Style.STROKE);//Brush color is gray Paint.setcolor (Color.parsecolor ("#D3D1D1"));//antialiasing Paint.setantialias (TRUE); Sets the color of the pen paint.setstrokewidth (2); Set the x-axis position of the switch circle Swithshilerx =-3; } @Overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas);//canvas.drawcolor (color.white);//button drawing switch// Draws a rounded rectangle that is drawn according to the size of the switch RECTF Re3 = new RECTF (0,0, Swithwidth*2-basewidth, swithwidth-baseheight); Canvas.drawroundrect (Re3, SWITHWIDTH/2, SWITHWIDTH/2, paint);//In drawing a picture of a control button, the x-axis is-3, is to let him move to the left of the x-axis a little Canvas.drawbitmap (Swithsilder,swithshilerx, 0, null);} @Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec, HEIGHTMEASURESPEC);//Set the size of the control to the size of the switch circle, you must set it, otherwise there is no way to calculate the current component's time size setmeasureddimension (Swithwidth*2-basewidth, Swithwidth); } @Overridepublic Boolean OntoucheVent (Motionevent event) {switch (event.getaction ()) {case MOTIONEVENT.ACTION_UP://Finger lifted CurrentState = (CurrentState = = True)? False:true; LOG.I ("Switch", currentstate+ ""); if (currentstate) {//sets the state of the drawn Rectangle Paint.setstyle (Paint.Style.FILL); Filling Paint.setcolor (color.green); Green//Set the position of the switch circle Swithshilerx = swithwidth-baseheight-3; }else{Paint.setstyle (Paint.Style.STROKE);//not filled with Paint.setcolor (Color.parsecolor ("#D3D1D1"));//Grey SW Ithshilerx =-3; }//Call the callback method, passing the current state mlistener.ontogglestatechange (CurrentState); Break } invalidate (); Refreshes the control, which invokes the OnDraw (canvas canvas) method to return true; Handle the event yourself, do not let the parent class consume the event}/** * External Setup Listener method * @param listener */public void Setontogglestatechangeli Stener (Ontogglestatechangelistener listener) {This.mlistener = listener; }//For setting when the state of the switch is changed, the upper layer calls this processing operationpublic interface ontogglestatechangelistener{/** * When switch state changes callback this method * Current switch status/void Ontogglestatechange (Boolean B); }}
Key points:
1. When we customize the view, we use coordinates that are our current view view, not relative to the entire screen.
2. Drawing a custom View key is drawing (OnDraw) and determining the size of the control (onmeasure)
With the above code my custom control is built and then can be used in the interface, here is to note that we are in the activity to set the callback event for the control, how to use:
<com.example.widget.switchbuttonview android:layout_width= "wrap_content" android:layout_height= " Wrap_content " android:id=" @+id/am_sbv " />
Private Switchbuttonview AM_SBV; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); AM_SBV = (Switchbuttonview) findViewById (R.ID.AM_SBV) ///Set the click Callback Event Am_sbv.setontogglestatechangelistener (new Ontogglestatechangelistener () {@Overridepublic void for the switch control Ontogglestatechange (Boolean B) {if (b) {log.i ("state", B + ", open");} ELSE{LOG.I ("state", B + ", Off");}});}
OK, so a custom switch space is complete, comrades, if you have any questions to ask, discuss
SOURCE download
Welcome reprint ....
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Custom Switch controls