[Android] sliding switch and androidswitch for Custom Controls

Source: Internet
Author: User

[Android] sliding switch and androidswitch for Custom Controls

~ Reprinted please indicate Source: http://blog.csdn.net/u013015161/article/details/46704745

Introduction

Last night, I wrote a SlideSwitch for Android. The effect is as follows:

Implementation

The idea of implementation is actually very simple. Listen to touch events on the control and refresh constantly. Let the slider draw at the position of the finger to achieve the Display Effect of sliding the slider along the finger.
First look at the Code:
SlideSwitch. java (modified on December 31, July 3: added a blank comment before calling onStateChangedListener In the touch event)

Package com. incell. view; import android. content. context; import android. graphics. canvas; import android. graphics. color; import android. graphics. paint; import android. util. attributeSet; import android. view. motionEvent; import android. view. view; public class SlideSwitch extends View {private Paint mPaint = new Paint (Paint. ANTI_ALIAS_FLAG); // boolean isOn = false; float curX = 0; float centerY; // y fixed floa T viewWidth; float radius; float lineStart; // position at the beginning of the line segment (horizontal coordinate, that is, float lineEnd; // position at the end of the line segment (ordinate float lineWidth; final int SCALE = 4; // control length: OnStateChangedListener onStateChangedListener; public SlideSwitch (Context context, AttributeSet attrs, int defStyle) {super (context, attrs, defStyle);} public SlideSwitch (Context context, AttributeSet attrs) {super (context, attrs);} public SlideSwi Tch (Context context) {super (context) ;}@ Override public boolean onTouchEvent (MotionEvent event) {// TODO Auto-generated method stub curX = event. getX (); if (event. getAction () = MotionEvent. ACTION_UP) {if (curX> viewWidth/2) {curX = lineEnd; if (false = isOn) {// The callback function is called only when the status changes, the same as if (null! = OnStateChangedListener) {onStateChangedListener. onStateChanged (true) ;}ison = true ;}} else {curX = lineStart; if (true = isOn) {if (null! = OnStateChangedListener) {onStateChangedListener. onStateChanged (false) ;}ison = false ;}}/* Call onDraw by refreshing */this. postInvalidate (); return true;} @ Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {// TODO Auto-generated method stub super. onMeasure (widthMeasureSpec, heightMeasureSpec);/* keep the width of SCALE/twice as high, that is, the diameter of the circle */this. setMeasuredDimension (this. getMeasuredWidth (), This. getMeasuredWidth () * 2/SCALE); viewWidth = this. getMeasuredWidth (); radius = viewWidth/SCALE; lineWidth = radius * 2f; // the straight line width is equal to the slider diameter curX = radius; centerY = this. getMeasuredWidth ()/SCALE; // centerY is half the height of lineStart = radius; lineEnd = (SCALE-1) * radius;} @ Override protected void onDraw (Canvas canvas Canvas) {// TODO Auto-generated method stub super. onDraw (canvas);/* limit the sliding range */curX = curX> LineEnd? LineEnd: curX; curX = curX <lineStart? LineStart: curX;/* dashes */mPaint. setStyle (Paint. style. STROKE); mPaint. setStrokeWidth (lineWidth);/* line on the left, green */mPaint. setColor (Color. BLUE); canvas. drawLine (lineStart, centerY, curX, centerY, mPaint);/* line on the right, gray */mPaint. setColor (Color. GRAY); canvas. drawLine (curX, centerY, lineEnd, centerY, mPaint);/* draw a circle * // * draw the leftmost and rightmost circles. The diameter is the width of the straight line segment, that is, add a semi-circle */mPaint on both sides of the line segment. 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 the listener for changing the switch status */public void setOnStateChangedListener (OnStateChangedListener o) {this. onStateChangedListener = o;}/* Internal interface, listener for switching status change */public interface OnStateChangedListener {public void onStateChanged (boolean state );}}

The comment should be detailed. There are mainly the following points.
1. Override the onMeasure method,Make the control highly dependent on the control width. In this way, no matter how configured in the layout fileEnsure control aspect ratio.
2. Control the activity range of the slider.
3. Define the internal interface OnStateChangedListener, and define its object in the custom control and the method setOnStateChangedListener that assigns values from the outside, so thatListens for switch status change events and calls callback.

Usage and Demo

Add the control to the layout file. The Demo effect is the animation display effect (the color in the demo is green, and the animation is blue because the green color causes problems during gif capturing and temporary changes ).
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

Package com. example. slideswitchexample; import com. example. slideswitchexample. slideSwitch. onStateChangedListener; import android. app. activity; import android. OS. bundle; import android. 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 (new OnStateChangedListener () {@ Override public void onStateChanged (boolean state) {// TODO Auto-generated method stub if (true = state) {Toast. makeText (MainActivity. this, "enabled", 1000 ). show ();} else {Toast. makeText (MainActivity. this, "the switch is off", 1000 ). show ();}}});}}

Click here to download the Demo project

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.