Android Custom Controls

Source: Internet
Author: User

Android Custom Controls
To develop a custom control, follow these steps: 1. Understand the working principle of the View. 2. Write a subclass inherited from the View. 3. Add attributes to the custom View class. 4. Draw controls. 5. respond to user messages. 6. Customize callback functions. 1. view structure principle the design of the View Structure of the Android system also adopts the combination mode, that is, View is the base class of all graphics, and Viewgroup extends its inheritance to View container class. View defines the basic operations of plotting. The basic operations are completed by three functions: measure (), layout (), and draw (). The internal operations include onMeasure () and onLayout () and onDraw () Sub-methods. The specific operation is as follows: 1. The measure operation is mainly used to calculate the size of a view, that is, the width and length of the view. The view is defined as the final type, and the subclass must not be modified. In the measure () function, the following function is called: (1) onMeasure (). The View Size is determined here. That is to say, measure is only a package for onMeasure, subclass can override the onMeasure () method to calculate the view size, and save 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 view is defined as the final type, and the subclass must not be modified. The layout () function has two basic operations: (1) setFrame (l, t, r, B), l, t, r, and B, that is, the specific position of the Child view in the parent view, this function is used to save these parameters. (2) onLayout (), in View, this function does not do anything. It is provided for the viewGroup type layout subview; 3. The draw operation uses the parameters obtained from the first two parts to display the view on the screen. The entire view is drawn here. Subclass should not modify this method either, because it defines the basic operations for plotting internally: (1) drawing the background; (2) if you want to view the gradient box, here we will do some preparation work; (3) Draw the view itself, that is, call the onDraw () function. In view, onDraw () 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, "NO content" contains multiple sub-views, and the sub-view has implemented its own rendering method, therefore, you only need to tell the sub-view to draw itself, that is, the following dispatchDraw () method; (4) Draw the sub-view, that is, the dispatchDraw () function. In view, this is an empty function. A specific view does not need to implement this method. It is specially prepared for the container class, that is, the container class must implement this method. (5) if necessary (the application calls setVerticalFadingEdge or setHorizontalFadingEdge), start to draw the gradient box; (6) Draw the scroll bar; From the above we can see that the custom View requires at least override onMeasure () and onDraw. 2. Three main ways to create custom controls using the View constructor: 1) inherit existing controls to implement custom controls: the main reason is that the control to be implemented is similar to the existing control in many aspects, and the requirements are met by extending the existing control. 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. 3. Two Methods for adding attributes to a custom View: 1) define attributes 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);    }    public MyView(Context context, AttributeSet attrs) {        super(context, attrs);        int resourceId = 0;        int textId = attrs.getAttributeResourceValue(null, "Text",0);        int srcId = attrs.getAttributeResourceValue(null, "Src", 0);        mtext = context.getResources().getText(textId).toString();        msrc = srcId;    }        @Override    protected void onDraw(Canvas canvas) {        Paint 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);    }    public MyImageView(Context context, AttributeSet attrs) {        super(context, attrs);        int 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. xml declares the attributes and stores the objects in the values directory.

 
     
                              
               
                       
  
 
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 defined in manifest.) You can then use uview: Oriental = "Vertical" like using system properties"
     
      
      
  
 
4. Draw onDraw () using controls 5,

6. Custom View Method

OnFinishInflate () callback method. When the application loads the component from XML and uses it to build the interface, onMeasure () is called to check the size of the View component and its child component onLayout () onDraw () onKeyDown when the component is about to plot its content onKeyDown when a keyboard is pressed onKeyUp when a keyboard is released onTrackballEvent when a trackball event occurs onTouchEvent when a touch screen event occurs onWindowFocusChanged (boolean) onAtrrachedToWindow () method triggered when the component gets or loses focus when it is put into a window onDetachedFromWindow () 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.