Android Custom Controls

Source: Internet
Author: User

To develop a custom control: 1, understand how view works 2, write subclass 3 Inheriting from view, add property 4 for Custom view class, draw control 5, respond to user message 6, custom callback functionFirst, view structure principleThe design of the view structure of the Android system also uses a combination pattern, that is, view as the base class for all the graphs, viewgroup to view inheritance as the Views container class. View defines the basic operation of the drawing basic operation is done by three functions: measure (), layout (), Draw (), and its interior contains onmeasure (), OnLayout (), OnDraw () three sub-methods. Here's how: 1, Measure operations      measure operations are primarily used to calculate the size of the view, which is the width and length of the view. Defined as the final type in view, requires that the subclass cannot be modified. The measure () function also calls the following function:      (1) onmeasure (), the view size will be finalized here, that is, measure is just a wrapper over Onmeasure, Subclasses can override the Onmeasure () method to achieve their own calculation of the view size, and save the calculation results by setmeasureddimension (width, height).  2, layout actions      layout actions are used to set where the view appears on the screen. Defined as the final type in view, requires that the subclass cannot be modified. There are two basic operations in the layout () function:      (1) setframe (l,t,r,b), l,t,r,b the specific location of the child view in the parent view, which is used to save these parameters;      (2) onlayout (), this function does nothing in view, it is provided primarily for ViewGroup type layout sub-views;  3, draw operations       The draw operation takes advantage of the parameters obtained from the first two parts, displays the view on the screen, and completes the entire view drawing work. Subclasses should also not modify the method because it internally defines the basic operation of the drawing:      (1) Draw background;      (2) If you want the view to display a gradient box, here are some preparations;      (3) Draws the view itself, which is called the OnDraw () function. OnDraw () is an empty function in view, which means that the specific view has to override the function to implement its own display (for example, the process of drawing text TextView here). And for VieWgroup does not need to implement this function, because as a container is "no content", it contains multiple sub-view, and the child view has implemented its own drawing method, so only need to tell the child view to draw their own, that is, the following Dispatchdraw () method;       (4) Draw a sub-view, the Dispatchdraw () function. In view this is an empty function, the specific view does not need to implement the method, it is specially prepared for the container class, that is, the container class must implement the method;      (5) If necessary (the application calls Setverticalfadingedge or Sethorizontalfadingedge), start drawing the gradient frame;      (6) Draw the scrollbar;      From above you can see that custom view requires a minimum of two onmeasure () and OnDraw () methods.  second, the construction method of view class3 main implementations of creating custom controls: 1) Inherit existing controls to implement custom controls: primarily when the controls to be implemented and the existing controls are similar in many ways, the requirements are met by extending the existing controls.    2) Implement a custom control by inheriting a layout file, which is typically done in this way when you make a composite control. Note that the OnDraw method is not used at this time, the layout file of the custom control is loaded by Inflater in the construction ad, and then the graphical interface of the custom control is loaded in AddView (view). 3) Implement a custom control by inheriting the view class, using GDI to draw the component interface, which is generally not possible in either of these ways.Iii. Two ways to customize view add attributes: 1) defined in the view class. Find the attribute name of the XML layout by using the AttributeSet introduced in the constructor, and then find the resource ID that corresponds to the reference to find the value. Case: Implement a picture with text (picture, text is OnDraw method redraw implementation)
 Public classMyViewextendsView {PrivateString Mtext; Private intMSRC;  PublicMyView (Context context) {Super(context); }     PublicMyView (Context context, AttributeSet attrs) {Super(context, attrs); intResourceId = 0; intTextid = Attrs.getattributeresourcevalue (NULL, "Text", 0); intSrcid = Attrs.getattributeresourcevalue (NULL, "SRC", 0); Mtext=context.getresources (). GetText (Textid). toString (); MSRC=srcid; } @Overrideprotected voidOnDraw (canvas canvas) {Paint Paint=NewPaint ();        Paint.setcolor (color.red); InputStream is=getresources (). Openrawresource (MSRC); Bitmap Mbitmap=Bitmapfactory.decodestream (IS); intBH =mbitmap.getheight (); intBW =mbitmap.getwidth (); Canvas.drawbitmap (Mbitmap,0,0, paint); //canvas.drawcircle (Max, Max, n, paint);Canvas.drawtext (Mtext, BW/2, 30, paint); }}

Layout file:

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" >    <Com.example.myimageview2.MyViewAndroid:id= "@+id/myview1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Text= "@string/hello_world"SRC= "@drawable/xh"/></LinearLayout>

Property text, SRC is read in the constructor method of the custom view class.

2) Register properties for view through XML. Same as the standard properties provided by Android. Case: Implement a textual description of the ImageView (imageview+textview combination, text description, you can set the location in the layout file)
 Public classMyimageviewextendsLinearLayout { PublicMyimageview (Context context) {Super(context);    }     PublicMyimageview (Context context, AttributeSet attrs) {Super(context, attrs);        intResourceId =-1; TypedArray TypedArray=context.obtainstyledattributes (Attrs, R.styleable.myimageview); ImageView IV=NewImageView (context); TextView TV=NewTextView (context); intN =Typedarray.getindexcount ();  for(inti = 0; i < N; i++) {            intattr =Typedarray.getindex (i); Switch(attr) { CaseR.styleable.myimageview_oriental:resourceid=Typedarray.getint (R.styleable.myimageview_oriental,0);  This. setorientation (ResourceId = = 1?)LinearLayout.HORIZONTAL:LinearLayout.VERTICAL);  Break;  CaseR.styleable.myimageview_text:resourceid=Typedarray.getresourceid (R.styleable.myimageview_text,0); Tv.settext (ResourceId> 0?typedarray.getresources (). GetText (resourceId): TypedArray. getString (                R.styleable.myimageview_text));  Break;  CaseR.styleable.myimageview_src:resourceid=Typedarray.getresourceid (R.STYLEABLE.MYIMAGEVIEW_SRC,0); Iv.setimageresource (ResourceId> 0?resourceid:r.drawable.ic_launcher);  Break;        }} AddView (iv);        AddView (TV);    Typedarray.recycle (); }}

Attrs.xml the attribute declaration, the file is placed in the values directory

<?XML version= "1.0" encoding= "Utf-8"?><Resources>    <declare-styleablename= "Myimageview">        <attrname= "Text"format= "Reference|string"></attr>        <attrname= "Oriental" >            <enumname= "Horizontal"value= "1"></enum>            <enumname= "Vertical"value= "0"></enum>        </attr>        <attrname= "SRC"format= "Reference|integer"></attr>    </declare-styleable></Resources>
Mainactivity layout file: First define the namespace xmlns:uview= "Http://schemas.android.com/apk/res/com.example.myimageview2" (Com.example.myimageview2 is the package name you define in manifest) and can then be used as if using the system's properties: Uview:oriental= "Vertical"
<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:uview= "Http://schemas.android.com/apk/res/com.example.myimageview2"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical"Tools:context=". Mainactivity " >    <TextViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "@string/hello_world" />    <Com.example.myimageview2.MyImageViewAndroid:id= "@+id/myimageview1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Uview:text= "This is a picture description"uview:src= "@drawable/tw"Uview:oriental= "Vertical">    </Com.example.myimageview2.MyImageView></LinearLayout>
Iv. Control Drawing OnDraw ()Five

Six: ways to customize View

The Onfinishinflate () callback method, which is called after the application loads the component from XML and constructs an interface with it, Onmeasure () detects the size of the view component and its subcomponents onlayout () when the component needs to allocate its child components to the location, Large hours Onsizechange () when the size of the component is changed OnDraw () when the component is about to draw its contents onkeydown when a keyboard is pressed onkeyup when a keyboard is released Ontrackballevent When a trackball event occurs Ontouchevent onwindowfocuschanged (Boolean) when the component gets and loses focus when the touch event occurs Onatrrachedtowindow () The method onwindowvisibilitychanged (int) that fires when the component is put into a window Ondetachedfromwindow () when the component is detached from a window: The method that fires when the visibility of the window containing the component changes

Android Custom Controls

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.