Android-the most simple custom switch button in history

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/48102871

Many times, we in a lot of Android or iOS app will encounter such an effect, there is a button, we click, will slide, one will show "on", one will show "off", this is the switch button, such as: Many Android phone settings function, There are a lot of features that are implemented with switch buttons, so how do these switch buttons work? Next, let's implement this feature together.

First, the principle

We put a background in an area of the interface A, the picture on the side of the "open" side for "off", in this picture to place a picture B, figure B is about half of figure A, just can cover the figure A on the "open" or "off", when we finger click on the picture, Figure B on Figure a slide, The corresponding overlay "on" or "off", so that the effect of the switch button is achieved.

II. Implementation 1, Custom view class Mytoggle

This class inherits from the view class to implement the Ontouchlistener interface at the same time, this class implements more functions, we decompose to see this class.

1) Attribute fields

Many attribute fields are defined in this class, and the specific meanings of each attribute field are described in the code comment

The specific implementation code is as follows:

Switch on background image private Bitmap bkgswitchon;//switch off background picture private Bitmap bkgswitchoff;//switch scrolling picture private Bitmap btnslip;// Whether the current switch is on, private boolean togglestateon;//switch State listener event private Ontogglestatelistener togglestatelistener;//record switch · The current state of the private Boolean istogglestatelisteneron;//the x-coordinate of the screen when the finger presses the private float prox;//the current x-coordinate of the finger slide in the private float currentx;// Whether the private Boolean isslipping;//record the state of the last switch, private boolean protogglestate = the rectangle private Rect when the true;//switch is on, is not in the slide state rect_on;// The rectangle private Rect Rect_off When the switch is off;

2) Constructing method of Overwrite view class

What we do in the construction method is to invoke the Init () method we created ourselves

The specific implementation code is as follows:

Public Mytoggle (Context context) {super (context); init (context);} Public Mytoggle (context context, AttributeSet Attrs) {Super (context, attrs); init (context);}

3) Create the Init method

The action implemented in this method is to set touch events.

The specific implementation code is as follows:

Initialization method private void init (context context) {Setontouchlistener (this);}

4) Finger Touch Event callback method Ontouch

This method is when the finger Operation phone screen, Android Automatic callback method, we in this method, listen to the finger's press, move and lift events, record the current x-coordinate of the finger to determine the direction of the movement of the picture B, so that the picture B on the picture a move to achieve button open and close effect.

The specific implementation code is as follows:

@Overridepublic boolean OnTouch (View V, motionevent event) {switch (event.getaction ()) {case motionevent.action_down:// Record the x-coordinate when the finger is pressed ProX = Event.getx (); CurrentX = prox;//Sets the sliding identity to trueisslipping = True;break;case motionevent.action_move://Records the current x-coordinate of the finger slide CurrentX = Event.getx (); break;case motionevent.action_up://when the finger is lifted, the identity of whether to slide is set to Falseisslipping = false;//is off if (CurrentX < Bkgswitchon.getwidth ()/2) {Togglestateon = false;} else {//is turned on togglestateon = true;} If a switch listener is used and the state of the switch changes, use the code if (Istogglestatelisteneron && togglestateon! = protogglestate) { Protogglestate = Togglestateon;togglestatelistener.ontogglestate (Togglestateon);} break;} Invalidate ();//Redraw return true;}

5) interface Redraw method OnDraw

The main implementation of this method is the interface redraw operation.

As long as the idea is:

Drawing background A:

The current finger sliding x-coordinate currentx is larger than the width of figure A, the button background is open;

The current finger sliding x-coordinate currentx is less than the width of the general, the button background is off state;

Record the x-coordinate of the slider B:

b When sliding:

The current finger slide x coordinate currentx is greater than the width of the background figure A, then B coordinates the width of figure A, minus the width of Figure B

The current finger slide x-coordinate currentx is less than the width of the background figure A, then the B coordinate is the current x-coordinate currentx minus half the width of the slider

B Stationary:

When the button is in the on State, the B coordinate is the leftmost x coordinate of the on state

When the button is in the off state, the B coordinate is the leftmost x coordinate of the off state

The specific implementation code is as follows:

@Overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas);//used to record the position of our slider int left_slip = 0; Matrix matrix = new Matrix (); Paint paint = new paint (), if (CurrentX < Bkgswitchon.getwidth ()/2) {//Draw a background picture on the canvas when the switch status is off  Canvas.drawbitmap ( Bkgswitchoff, matrix, paint);} else{//draws a  background image canvas.drawbitmap (Bkgswitchon, Matrix, paint) on the canvas when the switch status is on;} if (isslipping) {//switch is in slide state//Whether the slider exceeds the width of the entire slide button if (CurrentX > Bkgswitchon.getwidth ()) {//Specifies the position of the slider left_slip = Bkgswitchon.getwidth ()-Btnslip.getwidth ();} else {//sets the position of the current slider left_slip = (int) (Currentx-btnslip.getwidth ()/2);}} else {//whether the switch is in a   non-sliding state if (togglestateon) {left_slip = Rect_on.left;} else {left_slip = Rect_off.left;}} if (Left_slip < 0) {left_slip = 0;} else if (Left_slip > Bkgswitchon.getwidth ()-btnslip.getwidth ()) {Left_slip = bkgs Witchon.getwidth ()-Btnslip.getwidth ();} Draw Image Canvas.drawbitmap (Btnslip, Left_slip, 0, paint);}

6) Calculate the width and height of the switch

Here I calculate the width and height of the switch by covering the onmeasure.

The specific implementation code is as follows:

Calculates the switch's width height @overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {setmeasureddimension ( Bkgswitchon.getwidth (), Bkgswitchon.getheight ());}

7) Set up picture resource information

This method is primarily intended for external invocation and provides image resources to this class.

The specific code is implemented as follows:

/** * Set Picture resource information * @param bkgswitch_on * @param bkgswitch_off * @param btn_slip */public void setimageres (int bkgswitch_on, int bkgswitch_off, int btn_slip) {Bkgswitchon = Bitmapfactory.decoderesource (Getresources (), bkgswitch_on); Bkgswitchoff = Bitmapfactory.decoderesource (Getresources (), bkgswitch_off); btnslip = Bitmapfactory.decoderesource ( Getresources (), btn_slip), rect_on = new rect (Bkgswitchon.getwidth ()-Btnslip.getwidth (), 0,bkgswitchon.getwidth (), Btnslip.getheight ()); rect_off = new Rect (0, 0, btnslip.getwidth (), Btnslip.getheight ());}

8) Set the status of the switch button

By passing a Boolean-type state, we record this status identifier in this method.

The specific implementation code is as follows:

/** * Set the status of the switch button * @param state */public void Settogglestate (Boolean) {Togglestateon = states;}

9) Custom Switch status listener

In this class I have defined a switch state listener interface Ontogglestatelistener, which has a ontogglestate method to perform the button's state change monitoring operation.

The specific code is implemented as follows:

/** * Custom Switch Status listener * @author Liuyazhuang * */interface ontogglestatelistener {abstract void Ontogglestate (Boolean state);}

10) Set Switch listener

Create the Setontogglestatelistener method, pass a Ontogglestatelistener listener object, create Ontogglestatelistener objects from the outside, and pass the Ontogglestatelistener object in, we just have to record the Ontogglestatelistener object passed by the outside world. At the same time, when we call the Ontogglestate method in the Ontogglestatelistener interface, we implement the Ontogglestate method in the callback external Ontogglestatelistener implementation class.

The specific code is implemented as follows:

Sets the switch listener and sets whether the switch listener is set to Truepublic void Setontogglestatelistener (Ontogglestatelistener listener) { Togglestatelistener = Listener;istogglestatelisteneron = true;}

One) Mytoggle complete code is as follows:

Package Com.lyz.slip.toggle;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.graphics.matrix;import Android.graphics.paint;import Android.graphics.rect;import Android.util.attributeset;import Android.view.motionevent;import android.view.view;import android.view.view.ontouchlistener;/** * Custom Switch class * @author Liuyazhuang * */public class Mytoggle extends View implements Ontouchlistener {//switch on background image private Bitmap bkgswitchon;//switch Closed background picture private Bitmap bkgswitchoff;//switch scrolling picture private Bitmap btnslip;//Whether the current switch is on with private Boolean togglestateon;// Switch status Listener event private Ontogglestatelistener togglestatelistener;//record switch • Current state private Boolean istogglestatelisteneron;// The x-coordinate when the finger presses the screen private float prox;//the current x-coordinate of the private float currentx;//in the sliding state private Boolean isslipping;// Record the state of the last switch private boolean protogglestate = true;//switch on when the rectangle private rect rect_on;//switch off when the rectangle private rect rect_off;public Mytoggle (Context context) {Super (context); init (context);} Public Mytoggle (context context, AttributeSet Attrs) {Super (context, attrs); init (context);} Initialization method private void init (context context) {Setontouchlistener (this);} @Overridepublic boolean OnTouch (View V, motionevent event) {switch (event.getaction ()) {case motionevent.action_down:// Record the x-coordinate when the finger is pressed ProX = Event.getx (); CurrentX = prox;//Sets the sliding identity to trueisslipping = True;break;case motionevent.action_move://Records the current x-coordinate of the finger slide CurrentX = Event.getx (); break;case motionevent.action_up://when the finger is lifted, the identity of whether to slide is set to Falseisslipping = false;//is off if (CurrentX < Bkgswitchon.getwidth ()/2) {Togglestateon = false;} else {//is turned on togglestateon = true;} If a switch listener is used and the state of the switch changes, use the code if (Istogglestatelisteneron && togglestateon! = protogglestate) { Protogglestate = Togglestateon;togglestatelistener.ontogglestate (Togglestateon);} break;} Invalidate ();//Redraw return true;} @Overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas);//used to record the position of our slider int left_slip = 0; Matrix matrix = new MAtrix (); Paint paint = new paint (), if (CurrentX < Bkgswitchon.getwidth ()/2) {//Draw a background picture on the canvas when the switch status is off Canvas.drawbitmap ( Bkgswitchoff, matrix, paint);} else{//draws a background image canvas.drawbitmap (Bkgswitchon, Matrix, paint) on the canvas when the switch status is on;} if (isslipping) {//switch is in slide state//Whether the slider exceeds the width of the entire slide button if (CurrentX > Bkgswitchon.getwidth ()) {//Specifies the position of the slider left_slip = Bkgswitchon.getwidth ()-Btnslip.getwidth ();} else {//sets the position of the current slider left_slip = (int) (Currentx-btnslip.getwidth ()/2);}} else {//whether the switch is in a non-sliding state if (togglestateon) {left_slip = Rect_on.left;} else {left_slip = Rect_off.left;}} if (Left_slip < 0) {left_slip = 0;} else if (Left_slip > Bkgswitchon.getwidth ()-btnslip.getwidth ()) {Left_slip = bkgs Witchon.getwidth ()-Btnslip.getwidth ();} Draw Image Canvas.drawbitmap (Btnslip, Left_slip, 0, paint);} Calculates the switch's width height @overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {setmeasureddimension ( Bkgswitchon.getwidth (), Bkgswitchon.getheight ());} /** * Set Picture resource information * @param bkgswitch_on * @param bkgswitch_off * @param btn_slip */public void setimageres (int bkgswitch_on, int bkgswitch_off, int btn_slip) {Bkgswitchon = Bitmapfactory . Decoderesource (Getresources (), bkgswitch_on); Bkgswitchoff = Bitmapfactory.decoderesource (GetResources (), Bkgswitch_off); btnslip = Bitmapfactory.decoderesource (Getresources (), btn_slip); rect_on = new Rect ( Bkgswitchon.getwidth ()-Btnslip.getwidth (), 0,bkgswitchon.getwidth (), Btnslip.getheight ()); rect_off = new Rect (0, 0, Btnslip.getwidth (), Btnslip.getheight ());} /** * Set the status of the switch button * @param state */public void Settogglestate (Boolean) {Togglestateon = states;} /** * Custom Switch Status listener * @author Liuyazhuang * */interface ontogglestatelistener {abstract void Ontogglestate (Boolean state);} Sets the switch listener and sets whether the switch listener is set to Truepublic void Setontogglestatelistener (Ontogglestatelistener listener) { Togglestatelistener = Listener;istogglestatelisteneron = true;}}

2, Mainactivity

This class implementation is very simple, the main function is to load the interface layout, initialize the interface control, call the method in the Mytoggle class to implement the switch effect of the button
The specific code is implemented as follows:

Package Com.lyz.slip.toggle;import Android.app.activity;import Android.os.bundle;import android.widget.Toast; Import com.lyz.slip.toggle.mytoggle.ontogglestatelistener;/** * Program main entry * @author Liuyazhuang * */public class Mainactivity extends Activity {//Custom switch object private mytoggle toggle; @Override public void OnCreate (Bundle savedinstance        State) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main);                Toggle = (Mytoggle) Findviewbyid (R.id.toggle);                Set the switch to display the picture used Toggle.setimageres (R.drawable.bkg_switch, R.drawable.bkg_switch, R.drawable.btn_slip);                Sets the default state of the switch to true on state toggle.settogglestate (true); Set the switch's monitor toggle.setontogglestatelistener (new Ontogglestatelistener () {@Overridepublic void Ontogglestate (Boolean s Tate) {//TODO auto-generated Method stubif (state) {Toast.maketext (Getapplicationcontext (), "Toggle on", 0). Show ();} else { Toast.maketext (Getapplicationcontext (), "Switch Off", 0). Show ();}}); }}

3. layout file Activity_main.xml

Here I refer to my own definition of the view class Mytoggle.

The specific code is implemented as follows:

<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.lyz.slip.toggle.mytoggle        android:id= "@+id/toggle"        android:layout_width= "Wrap_content"        android:layout_height= "wrap_content"        android:layout_centerinparent= "true"/></relativelayout>

4, Androidmanifest.xml

The specific code is as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "    package=" Com.lyz.slip.toggle "    android:versioncode=" 1 "    android:versionname=" 1.0 ">    <USES-SDK        android:minsdkversion= "Ten"        android:targetsdkversion= "/>    <application        " Android:allowbackup= "true"        android:icon= "@drawable/ic_launcher"        android:label= "@string/app_name"        Android:theme= "@style/apptheme" >        <activity            android:name= "Com.lyz.slip.toggle.MainActivity"            android:label= "@string/app_name" >            <intent-filter>                <action android:name= " Android.intent.action.MAIN "/>                <category android:name=" Android.intent.category.LAUNCHER "/>            </intent-filter>        </activity>    </application></manifest>

Third, the Operation effect



Four, warm tips

You can go to link http://download.csdn.net/detail/l1028386804/9063331 download android custom switch button Implementation example full source code

In this example, for the sake of the aspect, I write some text directly in the layout file and the related class, Everyone in the real project to write these words in the String.xml file, in the external reference to these resources, remember, this is the most basic development knowledge and specifications as an Android programmer, I am here just to facilitate directly written in the class and layout files.

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

Android-the most simple custom switch button in history

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.