Custom Controls (1)-Click the Implement switch button toggle

Source: Internet
Author: User

The steps to customize the control, the main methods used:

1, the first need to define a class, inherit from the view, for inheriting the view of the class, you will need to implement at least one construction method; There are actually three construction methods here:

Public View is called when Java code creates a view (using new), and if it is a view populated from XML, it is not called.


Public View (context context, AttributeSet Attrs) This is called when the XML is created but no style is specified


Public View (context context, AttributeSet attrs, int defstyle) This is called when a style is added on the second base

So for this, if you don't use a style, we focus on the second construction method

2, for any one of the controls, it needs to be displayed on our interface, then definitely need to define its size;

Here Google provides a method:protected void onmeasure (int widthmeasurespec, int heightmeasurespec); we went to see the inside of this method, actually called the

protected final void setmeasureddimension (int measuredwidth, int measuredheight); This method, where the first parameter is the width of the view, the second parameter is the height of the view, so that we can set the view width of the height, But note that this is set to the units are pixels

3. For a control that needs to be displayed, we often need to determine its location:

This requires rewriting the onlayout method, but in practice this method does not use much when customizing the view because the control has no discretion over the location, and the decision is generally in the parent control.

4, for a control, need to show, we certainly need to draw it out, here we need to rewrite the OnDraw method to draw this control

5, when the control state changes, we will probably need to refresh the view display state, this time we need to call the invalidate () method, this method will actually recall the OnDraw method to redraw the control

6, in the process of defining the control, if you need to set a click event on the view, you can directly use the Setonclicklistener method, and do not need to write view.setonclicklistener;

7, in the layout file to define the custom control, note that the name to use the full class name , and because it is inherited from the view control, so in the XML file if it is the view itself properties can be used directly, such as Android: Layout_width , wait.

The key thing here is this OnDraw method, let's take a look:

/*** Method of Drawing view, drawing the contents of the current view*/@Overrideprotected voidOnDraw (canvas canvas) {//Super.ondraw (canvas);Paint Paint=NewPaint (); //turn on anti-aliasingPaint.setantialias (true); //Painting BackgroundCanvas.drawbitmap (backgroundbitmap, 0, 0, paint); //Draw the sliderCanvas.drawbitmap (Slidebutton, Slidebtn_left, 0, paint); }

OnDraw Method The parameter passed in is a canvas canvas object, which is actually less than the difference in Java, we want to draw on the canvas also need a brush, we also here to initialize it out of paint paint = new Paint (), while setting a antialiasing effect Paint.setantialias (True), then calls the Drawbitmap method, successively drawing the switch's background and the slider of the switch, respectively, into:

One thing to note here is that thedrawbitmap (Bitmap Bitmap, float left, float top, paint paint) method in the middle of the two float type parameters, Represents the coordinates of X and y in the upper-left corner of the drawing, respectively (the origin is set in the upper-left corner), so if we have a plot coordinate passed in 0, 0, then the switch will be in a closed state, here, we use a variable slidebtn_left for the slider to set its position , the Slidebtn_left value should be 0 for the off state, and the Slidebtn_left value should be the width of the backgroundbitmap (background) minus Slidebutton (slider) for the open state. ;

Here's a look at the specific code, the annotations are detailed:

Custom control's class Djswitch.java, inherited from view:

 PackageCom.example.test.view;ImportCOM.EXAMPLE.TEST.R;ImportAndroid.content.Context;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Paint;ImportAndroid.util.AttributeSet;ImportAndroid.view.View; Public classDjswitchextendsView {/*** When creating a view in code, this constructor method is called * Similar to the initWithFrame method in iOS *@paramContext*/     PublicDjswitch (Context context) {Super(context); //TODO auto-generated Constructor stub    }        /*** This construction method is called when creating a view in XML * similar to the Initwithcoder and awakefromnib methods in iOS *@paramContext *@paramAttrs*/     PublicDjswitch (Context context, AttributeSet attrs) {Super(context, attrs);    Initview (); }        /**Current switch Status*/    Private BooleanCurrentState =false; /*** Initialize View*/    Private voidInitview () {/** Loading an Image object from the repository * iOS UIImage *backgroundimage = [UIImage imagenamed:@ "APP_SWITCH_BG"]; * That is, Android image entity bitmap, can be considered as iOS UIImage * difference is that iOS uiimage can be obtained through the class method, Android inside is through the factory method to achieve*/switch_bg_img=Bitmapfactory.decoderesource (Getresources (), R.DRAWABLE.APP_SWITCH_BG); Switch_btn_img=Bitmapfactory.decoderesource (Getresources (), r.drawable.app_switch_btn); //Add ListenerSetonclicklistener (NewMyonswitchclicklistener ());//can be understood as the Addtarget method in iOS, or Addgesturerecognizer    }                Private intswitchbtnx; Private intSwitchbtny; PrivateBitmap switch_bg_img; PrivateBitmap switch_btn_img; Private classMyonswitchclicklistenerImplementsOnclicklistener {@Override Public voidOnClick (View v) {Switchbtnclick (); }    }            /**This method is called when clicked*/    Private voidSwitchbtnclick () {CurrentState= !CurrentState; Invalidate (); //similar to the [self Setneeddisplay] method in iOS} @Overrideprotected voidOnmeasure (intWidthmeasurespec,intHeightmeasurespec) {        Super. Onmeasure (Widthmeasurespec, Heightmeasurespec); //equivalent to setting the Cgsize property of this viewsetmeasureddimension (Switch_bg_img.getwidth (), Switch_bg_img.getheight ()); }                /*** The method of drawing view, drawing the contents of the current view, similar to the DrawRect method in iOS * iOS is drawn with the cgrect structure, and Android comes with a canvas object*/@Overrideprotected voidOnDraw (canvas canvas) {Super. OnDraw (canvas); Paint Paint=NewPaint ();//paint, pigment, Chinese meaningPaint.setantialias (true);//set anti-aliasing                /*** Picture Background * quartz2d also has similar API * UIImage *image = [UIImage imagenamed:@ "Hhaa"] * [Image D             Rawatpoint];  * [Image Drawinrect]; Place the picture on the left in the rectangle on the right and stretch*/Canvas.drawbitmap (switch_bg_img,0, 0, paint); //Draw Button        if(currentstate) {switchbtnx= Switch_bg_img.getwidth ()-switch_btn_img.getwidth (); } Else{switchbtnx= 0;            } canvas.drawbitmap (Switch_btn_img, Switchbtnx, Switchbtny, paint); }        }

Define it in the layout file:

<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"    >        <!--To clearly see the size and position of the view, define the background -    <Com.example.test.view.DJSwitchAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:background= "#ff0000"android:layout_centerinparent= "true"        /></Relativelayout>

Because there is no logic to write any clicks to trigger the business, just a simple control, so there is no more code in Mainactivity:

 Packagecom.example.test;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.Menu; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);    Setcontentview (R.layout.activity_main); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; }    }

Since then, a custom button has been completed and the result is as follows:

Custom Controls (1)-Click the Implement switch button toggle

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.