Android Custom Controls

Source: Internet
Author: User

This article is published in the NetEase blog, feel relatively good, so summed up to learn!

Steps to develop a custom control:

1 Understanding how View works

2 writing subclasses that inherit from view

3 adding properties to a custom view class

4 Drawing controls

5 Responding to user messages

6 Custom Callback Functions


First, how the view works

The 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:

The basic operation is done by three functions: measure (), layout (), Draw (), and its interior contains onmeasure (), OnLayout (), OnDraw () Three self-methods, specific operation:

1, measure operation is mainly used to calculate the view size, that is, the width and length of the view. Defined in view as the final type, requires that the subclass cannot be modified, the measure method implements its own calculation of the view size, and saves the calculation results through Setmeasureddimension (width,height).

2. The layout action is used to set the position that the view appears on the screen. Defined in view is also the final type, requiring subclasses to not be modified, the layout () function has two basic operations:

(1) setframe (l,t,r,b) These four small parameters are the exact location of the child view in the parent view, which is used to save these parameters.

(2) OnLayout in view this parameter does nothing, providing this function is mainly used for ViewGroup type layout sub-layouts.

3, draw operation using the parameters obtained by the first two functions to display the view on the screen, here also completed the entire view of the drawing work, the subclass should not modify the method, for its internal definition of the basic operation of the drawing:

(1) Draw the background:

(2) If you want the view to display a gradient box, here are some preparations

(3) Draw the view itself and call the OnDraw () function. The OnDraw method in view is an empty function, that is, the specific view will overwrite the function to achieve its own display, for example, TextView here to implement the process of drawing text. For ViewGroup, there is no need to implement this function, because as a container there is no content, it contains multiple sub-view, and the child view has implemented its own drawing, so only need to tell the child view to draw themselves can be called Dispatchdraw method.

(4) Draw a sub-view, that is, the Dispatchdraw method, in view 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, start drawing the gradient box.

(6) Draw the scroll bar, from the above can be seen that the custom view needs to overwrite at least onmeasure and OnDraw methods.

Second, the construction method of view class


There are 3 main implementations of creating custom controls:
1) Inherit existing controls to implement custom controls: primarily when the control you want to implement is similar to an existing control in many ways, by extending the existing control to meet the requirements.
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.


View (context context) simple constructor to use when    creating a view from code. View (context context, AttributeSet attrs)    Constructor that's called when inflating a view from XML. View (context context, AttributeSet attrs, int defstyle)    Perform inflation from XML and apply a class-specific base sty Le.
There are two ways to customize view Add properties:
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 class MyView extends View {private String mtext;private int msrc;public MyView (context context) {super (context);// Todo auto-generated constructor stub}public MyView (context context, AttributeSet Attrs) {Super (context, attrs);//Todo Au to-generated constructor Stubint resourceId = 0;int Textid = Attrs.getattributeresourcevalue (null, "Text", 0); int srcid = a Ttrs.getattributeresourcevalue (NULL, "SRC", 0); mtext = Context.getresources (). GetText (Textid). toString (); MSRC = Srcid;} @Overrideprotected void OnDraw (canvas canvas) {//TODO auto-generated method Stubpaint paint = new Paint ();p aint.setcolor (         color.red); InputStream is = Getresources (). Openrawresource (MSRC);                Bitmap Mbitmap = Bitmapfactory.decodestream (IS);        int bh = mbitmap.getheight ();        int bw = Mbitmap.getwidth (); Canvas.drawbitmap (Mbitmap, 0,0, paint),//canvas.drawcircle (Max, Max, N, Paint), Canvas.drawtext (Mtext, BW/2, +, Paint);}} Layout file: <?xml version= "1.0" encoding= "Utf-8"? ><linearlayoUT xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" Android:layout_ height= "match_parent" android:orientation= "vertical" > <com.example.myimageview2.myview android:id= "@+i D/myview1 "android:layout_width=" wrap_content "android:layout_height=" wrap_content "Text=" @string/he Llo_world "src=" @drawable/xh "/></linearlayout> property text, SRC read in the construction 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 class Myimageview extends LinearLayout {public Myimageview (context context) {super (context);//TODO Auto-generated Constructor Stub}public Myimageview (context context, AttributeSet Attrs) {Super (context, attrs);//TODO auto-generated constructor Stubint resourceId =-1; TypedArray TypedArray = context.obtainstyledattributes (Attrs,r.styleable.myimageview); ImageView IV = new ImageView ( context); TextView TV = new TextView (context), int N = Typedarray.getindexcount (), for (int i = 0; i < N; i++) {int attr = Typedarr Ay.getindex (i); switch (attr) {Case R.styleable.myimageview_oriental:resourceid = Typedarray.getint ( R.styleable.myimageview_oriental, 0); This.setorientation (resourceId = = 1?) LinearLayout.HORIZONTAL:LinearLayout.VERTICAL); Break;case R.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;case R.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-styleable Name= "Myimageview" > <attr name= "Text" format= "reference|string" ></attr> <attr name= "Orient Al "> <enum name=" Horizontal "value=" 1 "></enum> <enum name=" Vertical "value=" 0 " ;</enum> </attr> <attr name= "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 "can then be used as if using the system's properties: Uview:oriental=" Vertical "<linearlayout xmlns: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 "> <textview android:layout_width=" wrap_content "android:layout_height=" Wrap_content " android:text= "@string/hello_world"/> <com.example.myimageview2.myimageview android:id= "@+id/myImag EView1 "android:layout_width=" wrap_content "android:layout_height=" wrap_content "uview:text=" This is a picture description "Uview:src=" @drawable/tw "uview:oriental=" Vertical "> &LT;/COM.EXAMPLE.MYIMAGEVIEW2.MYIMAGEVIEW&GT;&L T;/linearlayout>

Iv. Control Drawing OnDraw ()


V. Ways to customize View
Onfinishinflate () callback method that is called when the application is loaded from XML and used to build the interface with it
Onmeasure () Detecting the size of the view component and its subcomponents
OnLayout () When the component needs to allocate its sub-component position, large hours
Onsizechange () When the size of the component is changed
OnDraw () When the component will draw its contents
OnKeyDown when a keyboard is pressed
OnKeyUp when you release a keyboard
Ontrackballevent when a trackball event occurs
Ontouchevent when a touch-screen event occurs
Onwindowfocuschanged (Boolean) When the component gets, loses focus
Onatrrachedtowindow () When the component is placed in a window
Ondetachedfromwindow () The method that is triggered when the component is detached from a window
onwindowvisibilitychanged (int): The method that fires when the visibility of the window that contains the component has changed

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Custom Controls

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.