Android (11) Sliding switch button

Source: Internet
Author: User

A. Slide the switch button:

Find a better resource always want to share, the following share this source code (need to leave the source code), by the way a few simple description of the class.

(1). Rect class:


You can probably see the meaning of the four parameters in rect, what do you mean by the four variables in rect and left,top,right,bottom?

R.left (Rectangle left): Popular is said to be in a distance from the x-axis of 0;

R.top (Rectangle top): Popular is said to be in a distance from the y axis 0;

R.right (Rectangle to the right): Popular is said to be in the distance of the y-axis of the distance;

R.bottom (Rectangular bottom): Popular is said to be in the distance from the y axis of B;


(2). Paint Class (Brushes): You can draw different colors and styles of graphics and text according to your own needs.

The main methods of the paint class are:

Setantialias: Sets the brush's jagged effect.

SetColor: Sets the color of the brush.

Setargb: Sets the a,r,p,g value of the brush.

Setalpha: Sets the alpha value.

Settextsize: Sets the size of the violet.

SetStyle: Sets the style of the brush, hollow or solid.


(3). Bitmap Class (bitmap): can be used to obtain image file information, image cutting, rotation, zooming and other operations, and can specify image file save operation

GetHeight (): Get bitmap width
GetWidth (): Get bitmap height
CreateBitmap (Bitmap src): Creating a bitmap instance from a bitmap resource
CreateBitmap (Bitmap source, int x, int y, int width, int height): Creates a bitmap at the specified position, zooms in and out bit source is a bitmap resource, (x, y) represents the upper-left coordinate of the bitmap, and width indicates the width of the bitmap , height indicates the bitmap height


(4). Canvas Class (Canvas): Drawing on the canvas, you also need to set some properties about the canvas, several common methods:

Canvas (): Creates an empty canvas. You can use the SetBitmap () method to set the specific canvas to draw.

Canvas (Bitmap): Creates a canvas with the Bitmap object, and the content is plotted on Bitmap, so Bitmap cannot be null.

Drawcolor: Sets the background color of the canvas.

ClipRect: Sets the display area.

Rotate: Rotates the canvas.


(5). Matrix class: The operation of the image.

Translate: Translation Transformation
Rotate: Rotation transformation
Scale: Scaling transformations
Skew: Split-cut transformation





Main interface:

public class Slipbuttonactivity extends Activity {private Slipbutton sb = null;private Button btn = null; @Overridepublic V OID onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Initview (); Setlistener ();} private void Setlistener () {sb. Setonchangedlistener (New Onchangedlistener () {public void OnChanged (Boolean checkstate) {Btn.settext (checkstate? "On": "Off");}); private void Initview () {sb = (Slipbutton) Findviewbyid (R.id.splitbutton); btn = (Button) Findviewbyid (R.id.ringagain); Sb.setcheck (True);}}

Layout:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:background=" @drawable/b        LUE_STRIPED_BG "android:orientation=" vertical "> <relativelayout android:id=" @+id/relativelayout1 "         Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_margintop= "15dip" android:padding= "5dip" > <button android:id= "@+id/ringagain" Android:layout_wid            Th= "Wrap_content" android:layout_height= "Wrap_content" android:layout_centerhorizontal= "true" android:background= "@drawable/clock_list" android:clickable= "false" android:gravity= "Center_ver             Tical "android:padding=" 10dip "android:text=" Turn On "android:textcolor=" @android: Color/black " Android:textsize= "18SP" /> <com.cn.slipbutton.slipbutton android:id= "@+id/splitbutton" android:layout_width= "1 00dip "android:layout_height=" 40dip "android:layout_alignright=" @id/ringagain "Android:la yout_aligntop= "@id/ringagain" android:layout_margintop= "10dip"/> </relativelayout></linearlayou T>

Custom View:

public class Slipbutton extends View implements Ontouchlistener {private Boolean nowchoose = false;//record whether the current button is open, true to open, F Lase to close Private Boolean ischecked;private boolean onslip = false;//record Whether the user is sliding the variable private float DOWNX, nowx;//pressed x, current XPRI Vate rect btn_on, btn_off;//in the open and closed state, the rect of the cursor. Private Boolean Ischglsnon = False;private Onchangedlistener Chglsn;privat E Bitmap bg_on, Bg_off, Slip_btn;public Slipbutton (context context) {super (context); init ();} Public Slipbutton (context context, AttributeSet Attrs) {Super (context, attrs); init ();} Public Slipbutton (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, defstyle); init ();} private void Init () {//Initialize bg_on = Bitmapfactory.decoderesource (Getresources (), r.drawable.split_left_1); Bg_off = Bitmapfactory.decoderesource (Getresources (), r.drawable.split_right_1); slip_btn = Bitmapfactory.decoderesource ( Getresources (), r.drawable.split_1); btn_on = new Rect (0, 0, slip_btn.getwidth (), Slip_btn.getheight ()); Btn_off = new Rect (bg_oFf.getwidth ()-Slip_btn.getwidth (), 0,bg_off.getwidth (), Slip_btn.getheight ()); Setontouchlistener (this);//Set Listener,        You can also directly replicate ontouchevent} @Overrideprotected void OnDraw (canvas canvas) {//Drawing function Super.ondraw (canvas); Manipulate the image matrix Matrix = new Matrix ();//Brush paint paint = new paint (); float x;if (Nowx < (Bg_on.getwidth ()/2)//slide to the first half Unlike the background of the second half, here's a judgment {x = Nowx-slip_btn.getwidth ()/2;canvas.drawbitmap (Bg_off, Matrix, paint);//Draw Close background}else {x = bg_on.ge Twidth ()-slip_btn.getwidth ()/2;canvas.drawbitmap (bg_on, Matrix, paint);//Draw the Open background}if (Onslip)//is in the sliding state, {if (Nowx & gt;= bg_on.getwidth ())//whether to underline the specified range, cannot let the cursor go outside, must make this judgment x = Bg_on.getwidth ()-slip_btn.getwidth ()/2;//minus the length of cursor 1/2 ... else if (Nowx < 0) {x = 0;} else {x = Nowx-slip_btn.getwidth ()/2;}} else {//non-sliding state if (nowchoose)//The position of the cursor is drawn according to the current switch state {x = Btn_off.left;canvas.drawbitmap (bg_on, Matrix, paint);// An open state picture should be drawn when the initial state is true} else{x = Btn_on.left;}} if (isChecked) {canvas.drawbitmap (bg_on, Matrix, paint); x = Btn_off.left;ischecked =!ischecked;} if (x < 0)//the cursor position is abnormal ... x = 0;else if (x > Bg_on.getwidth ()-Slip_btn.getwidth ()) x = Bg_on.getwidth ()-slip_btn    . getwidth (); Canvas.drawbitmap (slip_btn, x, 0, paint);//Draw travel mark.} public boolean OnTouch (View V, motionevent event) {//Execute code switch (event.getaction ()) According to action {case Motionevent.action_move ://Slide nowx = Event.getx (); Break;case motionevent.action_down://Press if (Event.getx () > bg_on.getwidth () | | event.gety () > Bg_on.getheight ()) return false;onslip = True;downx = Event.getx (); NOWX = Downx;break;case Motionevent.action_cancel://Move outside the control Onslip = False;boolean Choose = Nowchoose;if (NowX >= (bg_o N.getwidth ()/2)) {nowx = Bg_on.getwidth ()-Slip_btn.getwidth ()/2; Nowchoose = true;} else {nowx = Nowx-slip_btn.getwidth ()/2; Nowchoose = false;} if (Ischglsnon && (Choose! = Nowchoose))//If the listener is set, its method is called: Chglsn.onchanged (nowchoose); break;case motionevent.action_up://Release onslip = False;boolean LastChoose = NowChoose;if ( Event.getx () >= (bg_On.getwidth ()/2)) {nowx = Bg_on.getwidth ()-Slip_btn.getwidth ()/2; Nowchoose = true;} else {nowx = Nowx-slip_btn.getwidth ()/2; Nowchoose = false;} if (Ischglsnon && (lastchoose! = nowchoose))//If the listener is set, its method is called: Chglsn.onchanged (Nowchoose); break;default:}invalidate ();//Redraw control return true;} public void Setonchangedlistener (Onchangedlistener l) {//Set listener when state is modified Ischglsnon = true; CHGLSN = l;} Public interface Onchangedlistener {abstract void OnChanged (Boolean checkstate); public void SetCheck (Boolean isChecked) {this.ischecked = isChecked; Nowchoose = isChecked;}}





Android (11) Sliding switch button

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.