Android implementation slide switch component

Source: Internet
Author: User

Android implementation slide switch component

Because Android does not provide components such as slide switches, we need to implement a custom view component to achieve the slide switch effect.

Here is an example code, which includes three classes: switch component view, status listening interface, MainActivity

Let's take a look at the entire demo:

Let's take a look at the complete code of the view component. The Code has been commented out:

 

Package com. bear. swtichbuttondemo; import java. util. arrayList; 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 slide switch */public class MySwitchButton extends View implements OnTouchListener {private Bitmap switchOnBkg; // background private Bitmap switchOffBkg when the switch is enabled; // The background private Bitmap slipSwitchButton when the switch is off; // the picture of the sliding switch is private boolean isSlipping = false; // whether the private boolean isSwitchOn is sliding = false; // The status of the current switch. true indicates that the switch is enabled, and flase indicates that the private float previusx is disabled; // The horizontal coordinate xprivate float currentX when the finger is pressed; // The current horizontal coordinate Xprivate ArrayList
 
  
OnSwitchListenerList; // listener list public MySwitchButton (Context context, AttributeSet attrs) {super (context, attrs); init ();} private void init () {this. setOnTouchListener (this); // set the onSwitchListenerList = new ArrayList
  
   
();} Public void setImageResource (int switchBkg, int slipBtn) {switchOnBkg = BitmapFactory. decodeResource (this. getResources (), switchBkg); switchOffBkg = BitmapFactory. decodeResource (this. getResources (), switchBkg); slipSwitchButton = BitmapFactory. decodeResource (this. getResources (), slipBtn);} public void setSwitchState (boolean switchState) {this. isSwitchOn = switchState; this. invalidate ();} public boolean GetSwitchState () {return this. isSwitchOn;} public void setOnSwitchStateListener (OnSwitchListener listener) {onSwitchListenerList. add (listener) ;}@ Overrideprotected void onDraw (Canvas canvas) {super. onDraw (canvas); Matrix matrix = new Matrix (); Paint paint = new Paint (); float leftSlipBtnX; // The left coordinate of the sliding button // the canvas of the background image of the painting switch. drawBitmap (switchOnBkg, matrix, paint); if (isSlipping) {// if sliding if (currentX> switc HOnBkg. getWidth () {leftSlipBtnX = switchOnBkg. getWidth ()-slipSwitchButton. getWidth ();} else {leftSlipBtnX = currentX-slipSwitchButton. getWidth () ;}} else {// if no sliding if (isSwitchOn) {leftSlipBtnX = switchOnBkg. getWidth ()-slipSwitchButton. getWidth () ;}else {leftSlipBtnX = 0 ;}// if the finger slides out of the switch range, it should be processed like this if (leftSlipBtnX <0) {leftSlipBtnX = 0 ;} else if (leftSlipBtnX> switchOnBkg. getWidth ()-slipSwitchBu Tton. getWidth () {leftSlipBtnX = switchOnBkg. getWidth ()-slipSwitchButton. getWidth ();} // draw a toggle canvas on the canvas. drawBitmap (slipSwitchButton, leftSlipBtnX, 0, paint) ;}@ Overrideprotected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {super. onMeasure (widthMeasureSpec, heightMeasureSpec); setMeasuredDimension (switchOnBkg. getWidth (), switchOnBkg. getHeight () ;}@ Overridepublic boolean onTouch (View V, MotionEvent event) {// obtain the int action = event of the touch action type. getAction (); switch (action) {case MotionEvent. ACTION_MOVE: // if you are currently in the finger-moving state currentX = event. getX (); break; case MotionEvent. ACTION_DOWN: // if the current finger has just pressed the screen status isSlipping = true; break; case MotionEvent. ACTION_UP: // if the current finger has just left the screen status isSlipping = false; boolean previusstate = isSwitchOn; if (event. getX ()> (switchOnBkg. getWidth ()/2) {isSwitchOn = true;} else {isSw ItchOn = false;} // call the interface callback method to notify the listener object if (previusstate! = IsSwitchOn) {if (onSwitchListenerList. size ()> 0) {for (OnSwitchListener listener: onSwitchListenerList) {listener. onSwitched (isSwitchOn) ;}} break; default: break;} this. invalidate (); return true ;}}
  
 

Let's take a look at the code of the switch status listener interface, as shown below:

 

 

package com.bear.swtichbuttondemo;public interface OnSwitchListener {public abstract void onSwitched(boolean isSwitchOn);}

Finally, we will use the code in our Activity. here we need to upload two images to the custom component. Of course, you can also upload two self-prepared images. The Code is as follows:

 

 

Package com. bear. swtichbuttondemo; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. toast; public class MainActivity extends Activity {private MySwitchButton mySwitchButton; private Button myBtn; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanc EState); setContentView (R. layout. activity_main); setupViews ();} private void setupViews () {mySwitchButton = (MySwitchButton) findViewById (R. id. my_switch_button); // upload the image to the custom component mySwitchButton. setImageResource (R. drawable. switch_bkg_switch, R. drawable. switch_btn_slip); myBtn = (Button) findViewById (R. id. button); // set the switch status to listen to mySwitchButton. setOnSwitchStateListener (new OnSwitchListener () {@ Overridepublic void onSw Itched (boolean isSwitchOn) {if (isSwitchOn) {Toast. makeText (MainActivity. this: Toast. LENGTH_SHORT ). show ();} else {Toast. makeText (MainActivity. this: Toast. LENGTH_SHORT ). show () ;}}); myBtn. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {boolean isOn = mySwitchButton. getSwitchState (); mySwitchButton. setSwitchState (! IsOn );}});}}
 

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.