Android custom view Control and androidview Control

Source: Internet
Author: User

Android custom view Control and androidview Control

Reprinted from: develop 2. Compile a subclass that inherits the custom View 3. Add properties for the custom View Class 4. Draw controls 5. respond to user messages 6. Custom callback function 1. View Structure Principle Android system the view structure is also designed in a 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: copy the code public class MyView extends View {private String mtext; private int msrc to implement a text-carrying image (the image and text are repainted using the onDraw method; 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. get Resources (). 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) ;}} copy the code layout file: copy the Code <? 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 = "@ + id/myView1" android: layout_width = "wrap_content" android: layout_height = "wrap_content" Text = "@ string/hello_world" Src = "@ drawable/xh"/> </LinearLayout> copy the code attribute Text, src constructor in the Custom View class Read. 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) copy the code 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); T ExtView 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 () ;}} copy the code attrs. xml for Attribute declaration, the file is stored in the values directory to copy the Code <? Xml version = "1.0" encoding = "UTF-8"?> <Resources> <declare-styleable name = "MyImageView"> <attr name = "Text" format = "reference | string"> </attr> <attr name = "Oriental"> <enum name = "Horizontal" value = "1"> </enum> <enum name = "Vertical" value = "0"> </enum> </attr> <attr name = "Src" format = "reference | integer"> </attr> </declare-styleable> </resources> copy the layout file of the MainActivity code: first define the namespace xmlns: uview = "http://schemas.android.com/apk/res/com.example.myimageview2" (com. example. myimageview2 defines the package name for you in manifest) Then you can use: uview: Oriental = "Vertical" to copy code like using System Properties <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/myImageView1" android: layout_width = "wrap_content" android: layout_height = "wrap_content" uview: Text = "this is an image description" uview: src = "@ drawable/tw" uview: Oriental = "Vertical"> </com. example. myimageview2.MyImageView> </LinearLayout> copy Code 4. Draw onDraw () using the control 5 and 6: onFinishInflate () callback using the custom View method, onMeasure () method called after the application loads the component from XML and uses it to build the interface to detect the size of the View component and its child component onLayout () onDraw () onKeyDown when the component is about to draw 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.