Android Custom Slide Switch button

Source: Internet
Author: User

One

Second, the main technical points

1. Custom View

2. Custom Attributes

Iii. Steps for customizing controls

1. The custom class inherits from the view or view subclass;

2. Overriding the construction method

(1) MyView (Context); This method is called when the new object is in code

(2) MyView (Context,attributeset); This view is declared in an XML layout file, and is automatically called by the system when the object is created

(3) MyView (context,attributeset,int); As with Method 2 usage, just one more parameter: Default Style

3. Rewrite the method to achieve our requirements, generally to override the method:

(1) onmeasure (int,int); System measurement controls call this method for large hours

(2) OnLayout (Boolean,int,int,int,int); This method is called when the system specifies a location for the view, and the location of the child view is the only suggestion, and the decision is in the hands of the parent view. Overrides are generally not required.

(3) OnDraw (Canvas); This method is called when the content is drawn for this view.

Iv. to add a custom property to a new control:

1. Declare the attribute in the Attrs.xml file, with the attribute name (name) and format. Such as

<?XML version= "1.0" encoding= "Utf-8"?><Resources>    <!--declaring the name of a property set -    <declare-styleablename= "Mytogglebtn">        <!--Fame a property name is a My_background type reference to a reference type resource ID -        <attrname= "My_background"format= "Reference" />        <!--Fame a property name is a my_slide_btn type reference to a reference type resource ID -        <attrname= "My_slide_btn"format= "Reference" />        <!--Fame a property name is a curr_state type of Boolean type -        <attrname= "Curr_state"format= "Boolean" />    </declare-styleable></Resources>

2. Using the new property in the layout file, you must first declare the namespace, such as xmlns:gnnuit= "Http://schemas.android.com/apk/res/com.gnnuit.togglebutton", where "http ://schemas.android.com/apk/res/"for Android fixed format," Com.gnnuit.togglebutton "is the package name of the application, same as the package name declared by Androidmanifest.xml.

< Com.gnnuit.togglebutton.MyToggleButton         Android:layout_width = "Wrap_content"         android:layout_height= "Wrap_content"        gnnuit:curr_state= "true"         gnnuit:my_background= "@drawable/switch_background"        gnnuit:my_slide_btn  = "@drawable/slide_button"/>

3. In the construction method of the custom view, the desired property value is obtained by parsing the AttributeSet object.

Four. Core code

 PackageCom.gnnuit.togglebutton;ImportAndroid.content.Context;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Paint;ImportAndroid.util.AttributeSet;Importandroid.view.MotionEvent;ImportAndroid.view.View; Public classMytogglebuttonextendsViewImplementsAndroid.view.View.OnClickListener {PrivateBitmap Backgroundbitmap;//Background Image    PrivateBitmap Slidebuttonbitmap;//Slide button Picture    PrivatePaint paint; Private BooleanCurrentState =false;//Current status    Private floatLeft_slide;//left edge position of the slide button    Private floatStartX, LASTX;//record the start and end positions when sliding buttons are sliding    Private BooleanIsslide =false;//record whether to move the slide button    Private floatDist; /*** This view is declared in the layout file and is automatically called by the system when it is created *@paramContext *@paramAttrs*/     PublicMytogglebutton (Context context, AttributeSet attrs) {Super(context, attrs); //Get Custom PropertiesCurrentState = Attrs.getattributebooleanvalue ("Http://schemas.android.com/apk/res/com.gnnuit.togglebutton", "Curr _state ",false); intBackgroundresourceid = Attrs.getattributeresourcevalue ("http://schemas.android.com/apk/res/ Com.gnnuit.togglebutton "," My_background ",-1); if(Backgroundresourceid = =-1) {            Throw NewRuntimeException ("Please set background picture"); } Backgroundbitmap=Bitmapfactory.decoderesource (Getresources (), Backgroundresourceid); intSlidebtnresourceid = Attrs.getattributeresourcevalue ("Http://schemas.android.com/apk/res/com.gnnuit.togglebutton "," My_slide_btn ",-1); if(Slidebtnresourceid = =-1) {            Throw NewRuntimeException ("Please set background picture"); } Slidebuttonbitmap=Bitmapfactory.decoderesource (Getresources (), Slidebtnresourceid); if(currentstate) {left_slide= Backgroundbitmap.getwidth ()-slidebuttonbitmap.getwidth (); } initview ();//Initialize    }    /*** Initialize*/    Private voidInitview () {//Initialize picture//Backgroundbitmap = Bitmapfactory.decoderesource (Getresources (), r.drawable.switch_background); //Slidebuttonbitmap = Bitmapfactory.decoderesource (Getresources (), R.drawable.slide_button); //Initializing brushesPaint =NewPaint (); Paint.setantialias (true);//set anti-aliasing//set up Click eventsSetonclicklistener ( This); } @Override/*** Measurement of the size of the callback method*/    protected voidOnmeasure (intWidthmeasurespec,intHeightmeasurespec) {setmeasureddimension (Backgroundbitmap.getwidth (), Backgroundbitmap.getheight ());//sets the width and height of the control, in pixels} @Override/*** Draw the contents of the current view*/    protected voidOnDraw (canvas canvas) {Super. OnDraw (canvas); Canvas.drawbitmap (Backgroundbitmap,0, 0, paint); Canvas.drawbitmap (Slidebuttonbitmap, Left_slide,0, paint); } @Override Public voidOnClick (View v) {if(!isslide) {CurrentState= !CurrentState; Flushstate ();//Refresh Interface        }    }    /*** Refresh Current status*/    Private voidflushstate () {if(currentstate) {left_slide= Backgroundbitmap.getwidth ()-slidebuttonbitmap.getwidth (); } Else{left_slide= 0;    } invalidate (); } @Override Public Booleanontouchevent (Motionevent event) {Super. Ontouchevent (event); Switch(Event.getaction ()) { CaseMotionEvent.ACTION_DOWN:isSlide=false; StartX= LASTX =Event.getx ();  Break;  CaseMotionEvent.ACTION_MOVE:lastX=Event.getx (); Dist= Lastx-StartX; if(Math.Abs (Dist) > 5) {Isslide=true; Left_slide+=Dist;                Flushshow (); StartX=Event.getx (); }             Break;  Casemotionevent.action_up:if(isslide) {if(Left_slide > (Backgroundbitmap.getwidth ()-slidebuttonbitmap.getwidth ())/2) {Left_slide= Backgroundbitmap.getwidth ()-slidebuttonbitmap.getwidth (); CurrentState=true; } Else{left_slide= 0; CurrentState=false;            } flushshow (); }             Break; }        return true; }    /*** Refresh the current view*/    Private voidflushshow () {intMaxleftslide = Backgroundbitmap.getwidth ()-slidebuttonbitmap.getwidth (); //the range of Left_slide is 0=<left_slide<=maxleftslide        if(Left_slide >maxleftslide) {Left_slide=Maxleftslide; CurrentState=true; } Else if(Left_slide < 0) {Left_slide= 0; CurrentState=false;    } invalidate (); }}

Android Custom Slide Switch button

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.