Custom controls are like system controls: custom controls, drawing space pictures, defining spatial properties, constructing listeners.

Source: Internet
Author: User

Android's basic controls are difficult to meet the user's needs, so sometimes users need to customize some of the controls based on some of the artwork settings, not to mention, now, to customize the flow of a switch control to give you a better idea of how the control works:

1, first constructs a control class, inherits the view, this time needs to overwrite the view construction method. At the same time, you need to drag the artwork to the drawable directory, in order to be able to manually write code to build this control, you need to pass in the context of building this space, that is the context, and in the constructor method to initialize the class member variables. When the control is initialized, the picture that needs to be loaded into the artwork is: background bg and switch slide button swicher.

2, the Android control is through the view of the OnDraw () method to draw up, so to overwrite the view of the OnCreate method will be the BG and Swicher painted up. Drawing requires paper and pens, so when initializing a pen, the artboard system is provided, which is the canvas in the parameter. The parameters are graph, upper, left coordinate and pen. So what we want to set is the position of the picture is the coordinates of the upper left.

3, this time we can add this control in the XML file to see the effect, note that when adding space, you must add the package name and class name (do not bring class such as:< Com.example.togglebutton.ui.MytoggleButton can, at the same time, add the control's namespace: Copy Android and change Android to the package name of the program. Note that, by default, the size of the control is the length of the screen, so you need to call the Onmeasure () method to reset the width height.

4, in order to let the space can be dragged, you have to overwrite the view of the Ontouchevent () method, note that all the methods of touch events are handled by this method, and then listen to: Fall, Slide, leave the 3 actions (want more complex can also listen to other events), through the printing found can only hear " Fall "event, the original method is the default system processing, if you want the user to handle it, you must change the return surper.ontouchevent () to return true;

5, set the event processing, we draw according to the OnDraw method, set the coordinates when the left is set to the member variable of the class, on the 0, so when we change the value, and then call invalidate () Refresh operation call OnDraw () method to redraw.

6, set the properties of the control, here to add a state as a case, first create an XML file in the values, and then declare in the XML file, define the attribute Atrrs. If you do not remember, you can refer to the installation of the SDK directory under the Android custom properties definition: Sdk\platforms\android-19\data\res\values\attrs.xml. And in the construction method: Public Mytogglebutton (Context context, AttributeSet Attrs) parse the attribute, in the configuration file using the property, and set the default property value inside.

7. In the class, give the function to set state and get state, and state as the member variable of the function.

8, to set a monitoring event for the space, here defines a monitoring state changes in the interface, in the interface to declare the method of change in the states. The interface is then used as a member variable for the class, a function for the class to set the listener, an interface as an argument, so the setup listener must implement this interface and then copy the implementation interface to the class member variable.

9 in the Ontouchevent () up to determine whether the state changes, if the change is to use the instantiation of the interface class to invoke the interface OnChange method to complete the state release changes in the monitoring event.

The complete demo is given below:

Main.xml file

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:myview= "http// Schemas.android.com/apk/res/com.example.togglebutton.ui "xmlns:tools=" Http://schemas.android.com/tools "Android: Layout_width= "Match_parent" android:layout_height= "match_parent" android:paddingbottom= "@dimen/activity_vertical _margin "android:paddingleft=" @dimen/activity_horizontal_margin "android:paddingright=" @dimen/activity_ Horizontal_margin "android:paddingtop=" @dimen/activity_vertical_margin "tools:context=" Com.example.togglebutton.mainactivity$placeholderfragment "android:background=" #ffff00 "> <com.example.tog        Glebutton.ui.MytoggleButton android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Myview:state= "true" android:id= "@+id/togglebutton"/> <textview android:layout_width= "Wrap_c Ontent "android:layout_height=" wrap_content "android:id=" @+id/text "Android: Layout_centervertical= "True" android:layout_centerhorizontal= "true"/></relativelayout> 

The attribute definition file under values atrrs.xml file

<?xml version= "1.0" encoding= "Utf-8"? ><resources><declare-styleable name= "MyView" >   <attr Name= "state" format= "boolean"/>     </declare-styleable></resources>

Definition of a switch control class

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.graphics.drawable.bitmapdrawable;import android.text.Editable.Factory; Import Android.util.attributeset;import Android.view.motionevent;import Android.view.view;public class  Mytogglebutton extends View {private context context; private Bitmap bg;private Bitmap sw;private Paint paint;private int maxleft;private int Left;private Boolean state;private Onmytogglebuttonstatechangelitener onmytogglebuttonstatechangelitener;public void Setonmytogglebuttonstatechangelitener ( Onmytogglebuttonstatechangelitener l) {onmytogglebuttonstatechangelitener=l;} Public Mytogglebutton (Context context) {super (context); This.context=context;init ();} Here is the AttributeSet attrs of the parsing properties, which can be used in the configuration file public Mytogglebutton (context context, AttributeSet Attrs) {Super (context , attrs); This.context=context;init ();//Parse property string Namespace= "http://schemas.android.com/apk/res/ Com.example.togglebutton "; State=attrs.getattributebooleanvalue (namespace," state ", true);//default is off if (state==false) Left=0;elseleft=maxleft;} Public Mytogglebutton (context context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr); This.context=context;init ();} Initialize public void init () {paint=new paint (); Sw=bitmapfactory.decoderesource (Getresources (), R.drawable.slide_button_ background); Bg=bitmapfactory.decoderesource (Getresources (), r.drawable.switch_background); Maxleft=bg.getwidth ()-sw.getwidth ();} public void SetState (Boolean state) {if (state=true) {left=maxleft;state=true;} else {state=false;left=0;} Invalidate ();} public Boolean getState () {return state;} @Override//This is where space starts to run once protected void OnDraw (canvas canvas) {canvas.drawbitmap (bg, 0, 0, paint); Canvas.drawbitmap ( SW, left, 0,paint); Super.ondraw (canvas);} @Override//Limit space high width protected void onmeasure (int widthmeasurespec, int heighTmeasurespec) {super.onmeasure (Widthmeasurespec, Heightmeasurespec); Setmeasureddimension (Bg.getWidth (), Bg.getheight ());} int Startx=0;int currentx=0; @Overridepublic boolean ontouchevent (Motionevent event) {switch (event.getaction ()) {case motionevent.action_down:startx= (int) event.getx (); System.out.println ("Down" +state); break;case motionevent.action_move:currentx= (int) event.getx (); int d= Currentx-startx;left=d+left;if (Left>=maxleft) Left=maxleft;else if (left<=0) left=0; System.out.println ("move" +state); break;case MotionEvent.ACTION_UP:boolean stateolder=state; System.out.println ("Up" +state); if (LEFT&GT;MAXLEFT/2) {left=maxleft;state=true;} Else{left=0;state=false;} if (state!=stateolder&&onmytogglebuttonstatechangelitener!=null) Onmytogglebuttonstatechangelitener.statechange (GetState ()); break;default:break;} Invalidate ();//refresh drawing, call Space Ondrow () method return True;//super.ontouchevent (event);}

Activity file:

public class Mainactivity extends Activity {private Mytogglebutton togglebutton;private TextView tx;    @Override    protected void onCreate (Bundle savedinstancestate) {            super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);               togglebutton= (Mytogglebutton) Findviewbyid (R.id.togglebutton);        tx= (TextView) Findviewbyid (r.id.text);        Tx.settext ("state:" + (Togglebutton.getstate ()? ") Open ":" Off "));        Togglebutton.setonmytogglebuttonstatechangelitener (New Onmytogglebuttonstatechangelitener () {@Overridepublic void StateChange (Boolean state) {Tx.settext (' state: ' + (Togglebutton.getstate ()? ") (open ":"));}}        );}            }

  

Custom controls are like system controls: custom controls, drawing space pictures, defining spatial properties, constructing listeners.

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.