Android Custom Controls

Source: Internet
Author: User

Android Custom Controls

This article was published on the Netease blog. I think it is quite good. So let's take a look at it!

To develop a custom control, follow these steps:

1. Understand the working principle of View

2. Compile subclass inherited from View

3. Add attributes to the custom View class

4. Draw controls

5. respond to user messages

6. Custom callback function

 

I. View Working Principle

The view structure design of the Android system also adopts the combination mode, that is, the view is used as the base class of all graphics, and the viewgroup inherits the view as the view container class.

 

View defines the basic operations for drawing:

The basic operations are completed by three functions: measure (), layout (), and draw (). The functions include onMeasure (), onLayout (), and onDraw () three Self-methods:

1. The measure operation is mainly used to calculate the view size, that is, the width and length of the view. The view is defined as the final type and the subclass must not be modified. The measure method calculates the view Size and saves the calculation result through setMeasuredDimension (width, height.

2. The layout operation is used to set the position of the view displayed on the screen. The final type is also defined in the view, and the subclass must not be modified. The layout () function has two basic operations:

(1) setFrame (l, t, r, B) these four small parameters are the specific location of the Child view in the parent view. This function is used to save these parameters,

(2) The onLayout parameter does not do anything in the View. This function is provided mainly for the ViewGroup layout sub-layout.

3. The draw operation uses the parameters obtained by the first two functions to display the view on the screen. Now, the entire view is drawn. This method should not be modified by subclass, the basic operations for drawing are defined internally:

(1) Draw the background:

(2) If you want to display the gradient box in the view, some preparations will be made here.

(3) Draw the view itself and call the onDraw () function. In view, the onDraw method is an empty function. That is to say, a specific view must overwrite this function to display itself. For example, TextView implements the process of drawing text here. This function is not required for ViewGroup, because as a container, there is no content. It contains multiple sub-views, and the sub-View has implemented its own drawing, therefore, you only need to tell the sub-View to draw itself, that is, the dispatchDraw method.

(4) Draw a sub-view, that is, the dispatchDraw method, which is an empty function in the view. This method is not required for a specific view. It is specially prepared for the container class, that is, the container class must implement this method.

(5) If necessary, start to draw the gradient box.

(6) Draw a scroll bar. It can be seen from the above that at least the onMeasure and onDraw methods must be overwritten in the Custom view.

2. View class Constructor


Three main implementation methods for creating custom controls:
1) inherit the existing controls to implement custom controls: mainly when the controls to be implemented are similar to the existing controls in many aspects, the existing controls can be expanded to meet the requirements.
2) Implement custom controls by inheriting a layout file. Generally, this method can be used to combine controls.
Note that the onDraw method is not used at this time. In the construction of an advertisement, the layout file of the custom control is loaded through inflater, and then addView (view). The GUI of the custom control is loaded.
3) The custom control is implemented by inheriting the view class, and the component interface is drawn using GDI. This method is generally not available in the preceding two methods.

 

 

View(Context context)    Simple constructor to use when creating a view from code.View(Context context, AttributeSet attrs)    Constructor that is called when inflating a view from XML.View(Context context, AttributeSet attrs, int defStyle)    Perform inflation from XML and apply a class-specific base style.
3. Two Methods for adding attributes to a custom View:
1) defined in the View class. You can use AttributeSet introduced in the constructor to find the attribute name of the XML layout, and find the referenced resource ID to find the value.
Case: implement a text-carrying image (the image and text are repainted using the onDraw method)

 

 

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 Auto-generated constructor stubint resourceId = 0; int textId = attrs. getAttributeResourceValue (null, Text, 0); int srcId = attrs. 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 (); paint. 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 (40, 90, 15, paint); canvas. drawText (mtext, bw/2, 30, paint) ;}} layout file:
 
     
  
 The property Text and Src are read in the constructor of the custom View class.
2) Register attributes for the View through XML. Similar to the standard Attributes provided by Android.
Case: Implement an ImageView with text instructions (ImageView + TextView combination, text description, location can be set 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 = typedArray. 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. the xml file is stored in the values directory.
 
     
                              
               
                       
  
 MainActivity layout file: first defines the namespace xmlns: uview = Layout
     
      
       
   
  
 

4. Draw onDraw () using controls ()

 

 

5. Custom View Method
OnFinishInflate () callback method called after the application loads the component from XML and uses it to build the interface
OnMeasure () checks the size of the View component and its child components
OnLayout () when the component needs to be assigned the location and size of its child components
OnSizeChange () when the component size is changed
OnDraw () when the component is about to draw its content
OnKeyDown when you press a keyboard
OnKeyUp when a keyboard is released
OnTrackballEvent when a trackball event occurs
OnTouchEvent when a touch screen event occurs
OnWindowFocusChanged (boolean) when the component gets or loses focus
OnAtrrachedToWindow () when this component is put into a window
OnDetachedFromWindow () method triggered when the component is detached from a window
OnWindowVisibilityChanged (int): Method triggered when the visibility of the window containing this component changes
 

 

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.