Android Custom Control Series II: Custom Switch button (i)

Source: Internet
Author: User

This time we're going to implement a complete, purely custom control, instead of taking control of the system like the previous combo control; The plan is divided into three parts: the basic part of the custom control, the handling of the touch events of the custom control , and Custom properties for custom controls ;

Here is the first part of the writing, this time with a defined switch button for example, the following start:


First look at the effect, a click on the switch button to achieve the click Switch Status:



To be able to explain clearly, there are some basic introductions.

The first thing to be clear is the custom control or inherit from the view class, Google in the view of the class provides a lot of methods for us to use, using these methods we can achieve a considerable number of effects and functions, here need to use a few major methods;


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 control, it needs to display in 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 fact the method is not used much in custom view because the control has only the right of advice and no decision on the location. The right to decide is usually 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 the view itself is a property can be directly used, such as:android:layout_width Wait a minute


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


/** * Draw View method, draw the contents of the current View */@Overrideprotected void OnDraw (canvas canvas) {//Super.ondraw (canvas); Paint paint = new paint ();//Open anti-aliasing Paint.setantialias (true);//Draw Background Canvas.drawbitmap (backgroundbitmap, 0, 0, paint);// Draw Slider Canvas.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 here if we draw coordinates are passed 0, 0, then the switch will be in a closed state, here, we use a variable slidebtn_left slider to set its position, then for the off state, the value of Slidebtn_left should be 0, for the open state, the value of Slidebtn_left should be backgroundbitmap (background) width minus Slidebutton (slider) width ;


So, the mechanism is clearer, we just need to set a click event on the control, and set a Boolean variable to represent the state of the switch, and when clicked, toggle the Boolean variable to TRUE or false, while changing the value of Slidebutton is 0 or backgroundbitmap.getwidth ()-slidebutton.getwidth ()and then called invalidate () method to refresh the control, you can implement the basic switch function.


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


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

Package Com.example.togglebutton.ui;import Com.example.togglebutton.r;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.graphics.paint;import Android.util.attributeset;import android.view.view;/* * Several steps to customize view: * 1, First need to write a class to inherit from view * 2, need to get the object of the view, then you need to override the construction method, where one of the constructor method for new, two-parameter construction method for the use of XML layout file, three-parameter construction method can pass in a style * 3, the need to set the size of the view, Then you need to rewrite the Onmeasure method * 4, you need to set the location of the view, you need to override the OnLayout method, but this method in the custom view is not used much, mainly because the location of the view is mainly determined by the parent control * 5, Need to draw out the view you need to display, then you need to rewrite the OnDraw method * 6, when the control state changes, need to redraw the view, then call Invalidate (), method, this method will actually recall OnDraw method * 7, in which, If you need to set a click event on the view, you can call the Setonclicklistener method directly */public class Mytogglebutton extends View {/** * switch button background */private Bitmap BAC kgroundbitmap;/** * Switch button sliding part */private Bitmap slidebutton;/** * Sliding button left border */private float slidebtn_left;/** * Current switch status */PR  Ivate Boolean currentstate = false;/** * Use this construction method when creating objects inside the code * * @param context */public Mytogglebutton (context context) {Super(context);} /** * The view declared in the layout file is automatically called by the system when created * * @param context * @param attrs */public Mytogglebutton (context context, attributeset at TRS) {Super (context, attrs); Initview ();} /** * Callback method when measuring dimensions */@Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {//Super.onmeasure ( Widthmeasurespec, Heightmeasurespec);//Set the size of the current view Width:view the width of the pixel value Heigth:view, units are pixel values setmeasureddimension (Backgroundbitmap.getwidth (), Backgroundbitmap.getheight ());} This method is not helpful when customizing the view, because the location of the view is generally determined by the parent component @overrideprotected void OnLayout (Boolean changed, int left, int top, int Right,int bottom) {super.onlayout (changed, left, top, right, bottom);} /** * Draw View method, draw the contents of the current View */@Overrideprotected void OnDraw (canvas canvas) {//Super.ondraw (canvas); Paint paint = new paint ();//Open anti-aliasing Paint.setantialias (true);//Draw Background Canvas.drawbitmap (backgroundbitmap, 0, 0, paint);// Draw Slider Canvas.drawbitmap (Slidebutton, slidebtn_left, 0, paint);} /** * Initialize view */private void Initview () {backgroundbitmap = BitmapfactorY.decoderesource (Getresources (), r.drawable.switch_background); Slidebutton = Bitmapfactory.decoderesource ( Getresources (), R.drawable.slide_button);/* * Click event */setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {currentstate =!currentstate;flushstate (); Flushview ();}});} /** * Refresh view */protected void Flushview () {//Refresh current view will result in OnDraw method execution invalidate ();} /** * Refreshes the current state */protected void Flushstate () {if (currentstate) {slidebtn_left = Backgroundbitmap.getwidth ()-Slidebutton. GetWidth ();} else {slidebtn_left = 0;}}}


Define it in the layout file:


<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 "    tools:context= "${relativepackage}.${activityclass}" >    < Com.example.togglebutton.ui.MyToggleButton        android:id= "@+id/my_toggle_btn"        android:layout_width= "Wrap_ Content "        android:layout_height=" wrap_content "        android:layout_centerinparent=" true "/></ Relativelayout>


In this case, because there is no logic to write any clicks to trigger the business, just a simple control, so there is no more code in the mainactivity:


Package Com.example.togglebutton;import Android.app.activity;import Android.os.bundle;public class MainActivity Extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);}}


At this point a custom switch button is completed, the next two will show how to implement the click-drag switch on the effect and how to implement the custom properties, thank you for your support!

Android Custom Control Series II: Custom Switch button (i)

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.