Android Imitation apple IOS6 switch button _android

Source: Internet
Author: User
Tags border color getcolor

First to show you the effect of the picture:

Do not know how you feel about the effect of the picture, personal sleep is also good, interested friends can refer to the implementation of the code OH.

public class ToggleButton extends View {private Springsystem springsystem; private Spring spring;/** * Private float
Radius
/** Open Color */private int oncolor = Color.parsecolor ("#4ebb7f");
/** Close Color */private int offbordercolor = Color.parsecolor ("#dadbda");
/** Gray with color/private int offcolor = Color.parsecolor ("#ffffff");
/** Handle color */private int spotcolor = Color.parsecolor ("#ffffff");
/** Border Color */private int bordercolor = Offbordercolor;
/** Brush * * Private Paint Paint;
/** Switch State * * Private Boolean toggleon = false;
/** Border Size * * Private int borderwidth = 2;
/** Vertical Center * * Private float centery;
/** button start and end position * * Private float startx, endx;
/** handle x position of the minimum and maximum value * * Private float spotminx, Spotmaxx;
/** Handle Size * * private int spotsize;
/** handle x Position * * Private float spotx;
/** closed when the internal gray belt height * * Private float offlinewidth;
/** * * Private RECTF rect = new RECTF ();
/** default use of animation/private Boolean defaultanimate = true;
/** whether the default is open */private Boolean Isdefaulton = false;
Private ontogglechanged listener; Private Togglebutton (context) {super (context);} public ToggleButton (context context, AttributeSet attrs, int defstyleattr) {Supe
R (Context, attrs, defstyleattr);
Setup (ATTRS); ToggleButton (context, AttributeSet attrs) {Super (context, attrs), Setup (attrs); @Override protected Vo ID Ondetachedfromwindow () {Super.ondetachedfromwindow (); Spring.removelistener (Springlistener);} public void Onattachedtowindow () {Super.onattachedtowindow (); Spring.addlistener (Springlistener);} public void Setup ( AttributeSet attrs) {paint = new paint (Paint.anti_alias_flag); Paint.setstyle (Style.fill); Paint.setstrokecap (
Cap.round);
Springsystem = Springsystem.create ();
Spring = springsystem.createspring ();
Spring.setspringconfig (Springconfig.fromorigamitensionandfriction (50, 7));
This.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View arg0) {toggle (defaultanimate);}});
TypedArray TypedArray = GetContext (). Obtainstyledattributes (Attrs, R.styleable.togglebutton); OfFbordercolor = Typedarray.getcolor (R.styleable.togglebutton_tboffbordercolor, Offbordercolor);
Oncolor = Typedarray.getcolor (R.styleable.togglebutton_tboncolor, Oncolor);
Spotcolor = Typedarray.getcolor (R.styleable.togglebutton_tbspotcolor, Spotcolor);
Offcolor = Typedarray.getcolor (R.styleable.togglebutton_tboffcolor, Offcolor);
BorderWidth = Typedarray.getdimensionpixelsize (R.styleable.togglebutton_tbborderwidth, borderWidth);
Defaultanimate = Typedarray.getboolean (r.styleable.togglebutton_tbanimate, defaultanimate);
Isdefaulton = Typedarray.getboolean (R.styleable.togglebutton_tbasdefaulton, Isdefaulton);
Typedarray.recycle ();
BorderColor = Offbordercolor;
if (Isdefaulton) {Toggleon ();}} public void Toggle () {Toggle (true);} public void Toggle (Boolean animate) {Toggleon =!toggleon; Takeeffect (animate); if (Listener!= NULL)
{Listener.ontoggle (Toggleon);} 
public void Toggleon () {Settoggleon (), if (listener!= null) {Listener.ontoggle (Toggleon);}} public void Toggleoff () { SeTtoggleoff ();
if (listener!= null) {Listener.ontoggle (Toggleon);}} The/** * setting is displayed as an open style and does not trigger the toggle Event/public void Settoggleon () {Settoggleon (true);}/** * @param animate ASD/public void S Ettoggleon (Boolean animate) {Toggleon = true; Takeeffect (animate);}/** * settings are displayed as closed styles and do not trigger toggle events/public void Settoggle  Off () {Settoggleoff (TRUE);} public void Settoggleoff (Boolean animate) {Toggleon = false; Takeeffect (animate);} private void Takeeffect (Boolean animate) {if (animate) {Spring.setendvalue (toggleon? 1:0);} else{//Spring is not invoked here, so the current value in spring is not changed, set here to synchronize the current values on both sides spring.setcurrentvalue (Toggleon? 1:0); Calculateeffect ( Toggleon?
1:0); } @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {final int widthmode = measurespec.ge
Tmode (WIDTHMEASURESPEC);
Final int heightmode = Measurespec.getmode (Heightmeasurespec);
int widthsize = measurespec.getsize (Widthmeasurespec);
int heightsize = measurespec.getsize (Heightmeasurespec); Resources R = ResourceS.getsystem (); if (Widthmode = = Measurespec.unspecified | | widthmode = = measurespec.at_most) {widthsize = (int)
Typedvalue.applydimension (Typedvalue.complex_unit_dip, R.getdisplaymetrics ());
Widthmeasurespec = Measurespec.makemeasurespec (widthsize, measurespec.exactly); } if (Heightmode = measurespec.unspecified | | heightsize = = measurespec.at_most) {heightsize = (int) typedvalue.applydime
Nsion (Typedvalue.complex_unit_dip, R.getdisplaymetrics ());
Heightmeasurespec = Measurespec.makemeasurespec (heightsize, measurespec.exactly);
} super.onmeasure (Widthmeasurespec, Heightmeasurespec); @Override protected void OnLayout (Boolean changed, int left, int. top, int right, int bottom) {super.onlayout (changed, l
EFT, top, right, bottom);
Final int width = getwidth ();
Final int height = getheight ();
Radius = math.min (width, height) * 0.5f;
CenterY = radius;
StartX = radius;
EndX = Width-radius;
Spotminx = StartX + borderwidth;
Spotmaxx = Endx-borderwidth; spotsize = height-4 * BORDERWIdth; Spotx = Toggleon?
Spotmaxx:spotminx;
offlinewidth = 0; 
Simplespringlistener Springlistener = new Simplespringlistener () {@Override public void onspringupdate (Spring spring) {
Final Double value = Spring.getcurrentvalue ();
Calculateeffect (value);
}
}; private int clamp (int value, int low, int high) {return math.min (Math.max (value, low), high);} @Override the public void DRA W (Canvas Canvas) {//rect.set (0, 0, getwidth (), getheight ()); Paint.setcolor (bordercolor); Canvas.drawroundrect (Rect,
Radius, radius, paint); if (Offlinewidth > 0) {final float cy = offlinewidth * 0.5f; Rect.set (Spotx-cy, Centery-cy, EndX + cy, CenterY + cy)
;
Paint.setcolor (Offcolor);
Canvas.drawroundrect (Rect, CY, CY, paint);
} rect.set (SpotX-1-radius, Centery-radius, Spotx + 1.1f + radius, centery + radius);
Paint.setcolor (bordercolor);
Canvas.drawroundrect (Rect, radius, radius, paint);
Final float SPOTR = spotsize * 0.5f; Rect.set (SPOTX-SPOTR, CENTERY-SPOTR, Spotx + SPOTR, CenterY + SPOTR);
Paint.setcolor (Spotcolor);
Canvas.drawroundrect (Rect, SPOTR, SPOTR, paint); }/** * @param value */private void Calculateeffect (final double value) {final float Maptogglex = (float) springutil.map
Valuefromrangetorange (value, 0, 1, Spotminx, Spotmaxx);
Spotx = Maptogglex;
float mapofflinewidth = (float) springutil.mapvaluefromrangetorange (1-value, 0, 1, spotsize);
Offlinewidth = Mapofflinewidth;
Final int fb = Color.Blue (Oncolor);
Final int fr = color.red (oncolor);
Final int FG = Color.green (Oncolor);
Final int tb = Color.Blue (Offbordercolor);
Final int tr = color.red (Offbordercolor);
Final int tg = Color.green (offbordercolor);
int sb = (int) springutil.mapvaluefromrangetorange (1-value, 0, 1, FB, TB);
int sr = (int) springutil.mapvaluefromrangetorange (1-value, 0, 1, FR, TR);
int sg = (int) springutil.mapvaluefromrangetorange (1-value, 0, 1, FG, TG);
SB = Clamp (SB, 0, 255);
SR = Clamp (SR, 0, 255);
SG = CLAMP (SG, 0, 255);
BorderColor = Color.rgb (SR, SG, SB); Postinvalidate (); 
}/** * @author ThinkPad * */public interface ontogglechanged{/** * @param on = = */public void Ontoggle (Boolean on); public void setontogglechanged (ontogglechanged ontogglechanged) {listener = ontogglechanged;} public boolean isanimate ( {return defaultanimate} is public void Setanimate (Boolean animate) {this.defaultanimate = animate;}}

Don't forget the custom attribute: Attrs.xml

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
<declare-styleable name= "ToggleButton" >
<attr name= "Tbborderwidth" format= "Dimension"/> <attr name= "Tboffbordercolor"
Reference|color "/> <attr name= tboffcolor" format= "Reference|color"/> <attr name= "
tbOnColor" format= "Reference|color"/> <attr name= "Tbspotcolor" format= "Reference|color"/> <attr "name="
Tbanimate "format=" Reference|boolean "/> <attr name=" Tbasdefaulton "format=" Reference|boolean "/>
</declare-styleable>
</resources>

Main.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout 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" xmlns:toggle= "Http://schemas.android.com/apk/res-auto" android:orientation= "vertical" > < LinearLayout android:layout_margintop= "10DP" android:layout_width= "match_parent" android:gravity= "Center_ Horizontal "android:layout_height=" wrap_content "> <com.example.ekikousei.view.togglebutton android:id=" @+id /mtogglebutton01 "android:layout_width=" 54DP "android:layout_height=" 30DP "> </ com.example.ekikousei.view.togglebutton> </LinearLayout> <linearlayout android:layout_margintop= "10DP "Android:layout_width=" match_parent "android:gravity=" Center_horizontal "android:layout_height=" Wrap_content "
> <com.example.ekikousei.view.togglebutton android:id= "@+id/mtogglebutton02" android:layout_width= "54DP" Android:layout_height= "30DP"Toggle:tbborderwidth=" 2DP "toggle:tboffbordercolor=" "#000" toggle:tboffcolor= "#ddd" toggle:tboncolor= "#f00" toggle : tbspotcolor= "#00f" > </com.example.ekikousei.view.ToggleButton> </LinearLayout> </linearlayout >

Maintivity

public class Mainactivity extends activity {
private ToggleButton mToggleButton01;
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
MToggleButton01 = (ToggleButton) Findviewbyid (r.id.mtogglebutton01);
Mtogglebutton01.setontogglechanged (New togglebutton.ontogglechanged () {
@Override public
void Ontoggle ( Boolean on) {
if (on) {
toast.maketext (mainactivity.this, open, Toast.length_short). Show ();
else {
Toast.maketext (mainactivity.this, "Default shutdown", Toast.length_short). Show ();}}}

JAB here: Studio click to download

The above is a small set to introduce the Android imitation Apple IOS6 switch button, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.