[Android Custom Controls] Android Custom Controls

Source: Internet
Author: User
Tags gettext

To develop a custom control: 1, understand how view works  2, write subclass 3 Inheriting from view, add attribute  4 for custom view class, draw control  5, respond to User message  6, customize callback function     A, view structure principle the design of the structure of the Android system also adopts the combination mode, that is, view as the base class of all the graphs, and 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, this will doSome preparatory work;      (3) Draw the view itself, that is, call 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). For ViewGroup, you do 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 () Methods;      (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.   The construction method of view Class 3 main implementations of creating custom controls: 1) Inherit existing controls to implement custom controls: mainly when the control to be implemented and the existing control are similar in many ways, by extending the existing controls 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 at this point, the OnDraw method is not used, 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.   The two ways to customize view add properties are: 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);        } 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 (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:o rientation= "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>

  

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 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 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= "Oriental" >            < 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" (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"
<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 a picture stating "         uview:src=" @drawable/tw "        uview:oriental=" Vertical ">    < /com.example.myimageview2.myimageview></linearlayout>

  

Four, the control draws the 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] 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.