[Android] toggle button-Custom control

Source: Internet
Author: User

Prepare two pictures, a button background, a small switch on the top

Create a class mytogglebtn, inherit View

Implement three construction methods, pass the context,

Implements the constructor method, passing the Context object, which is used primarily when instantiated in Java code.

Implements the construction method, passes the Context object,attributeset The object, the main use in the layout file

The View object is displayed on the screen, and there are several important steps

1. Construct a method to create an object

2. Measuring the size of the view onseasure (int,int)

3. Determine the location of the view , theview itself has some suggestions, the decision right in the hands of the Father view onlayout ()

4. Draw the contents of the view onDraw (Canvas)

Constructs a method, initializes the view,

Call the Bitmapfactory.decoderesurce () method to turn the picture resource into A Bitmap object, parameter:Resource Object (getresources ()), resource ID

Override the onmesaure () method,

Do not call the parent class

Call the setmeasureddimension () method, Parameters: Width, height, call background Bitmap object getwidth () , and getheight ()

Override the OnDraw () method to pass in the Canvas Object

Call the Drawbitmap () method of the Canvas object, parameter:Bitmap object, left point (0 ), top point (0),Paint Object

Get the Paint object,new out

Call the Paint object's setantialias (), set anti-aliasing, parameters: Boolean

Slide button

Slide button Current position,0,0, state is off

Canvas.drawbitmap (bitmapbtn, 0, 0, paint);

The position of the slide button is in the width of the background graph - the width of the slide button,0, the state is open

Canvas.drawbitmap (bitmapbtn, width of the background map - slide button width , 0, paint);

Define member variable currentstate Store Current state, Value: Boolean value

Call the Setonclicklistener () method, set the Click event, Parameters: this

The current class implements the Obclicklistener interface to implement the OnClick () method

Toggle Current state Currentstate=!currentstate

Judging the current state

If true, the left side of the slide button is the width of the background graph - the width of the slide button

If False, the left side of the slide button is 0

Call the invalidate () method to refresh the current view

Mytogglebtn.java

 Packagecom.tsh.myswitchbtn;ImportAndroid.content.Context;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Paint;ImportAndroid.util.AttributeSet;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener; Public classMytogglebtnextendsViewImplementsOnclicklistener {//Background Image    PrivateBitmap Bitmapbackground; //button Picture    PrivateBitmap bitmapbtn; PrivatePaint paint; /*** used in Layout files *@paramContext *@paramAttrs*/     Publicmytogglebtn (Context context, AttributeSet attrs) {Super(context, attrs);    Initview (); }    /*** Initialize View*/    Private voidInitview () {Bitmapbackground=Bitmapfactory.decoderesource (Getresources (), r.drawable.switch_background); BITMAPBTN=Bitmapfactory.decoderesource (Getresources (), R.drawable.slide_button); Paint=NewPaint (); Paint.setantialias (true); //Click eventsSetonclicklistener ( This); }    /*** Calculate Size*/@Overrideprotected voidOnmeasure (intWidthmeasurespec,intHeightmeasurespec)    {setmeasureddimension (Bitmapbackground.getwidth (), Bitmapbackground.getheight ()); }    //Current status    Private BooleanCurrentstate=false; //the current left of the slide button    Private floatSlidebtnleft=0; /*** Draw View*/@Overrideprotected voidOnDraw (canvas canvas) {//Draw BackgroundCanvas.drawbitmap (bitmapbackground, 0, 0, paint); //Draw Slide ButtonsCanvas.drawbitmap (bitmapbtn, Slidebtnleft, 0, paint); }    /*** Click events*/@Override Public voidOnClick (View v) {currentstate=!CurrentState; if(currentstate==true) {Slidebtnleft=bitmapbackground.getwidth ()-bitmapbtn.getwidth (); }Else{slidebtnleft=0;    } invalidate (); }}

Layout:

<Relativelayoutxmlns: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"Tools:context= "${relativepackage}.${activityclass}" >    <Com.tsh.myswitchbtn.MyToggleBtnandroid:layout_centerinparent= "true"Android:id= "@+id/my_toggle_btn"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"        /></Relativelayout>

[Android] toggle button-Custom control

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.