Create custom component building M Components

Source: Internet
Author: User
Create custom component building M Components

Android provides an exquisite and powerful componentized mode to create your user interface. It is based on the basic layout class: View and view group viewgroup. The platform contains a variety of pre-defined views and view group subclasses-known as components and layout-which can be used to construct your user interface.

Some of the available components include button, Text View textview, edit text box edittext, list view listview, combox checkbox, single choice button radiobutton, gallery Gallery, fine-tuning machine spinner, and some autocompletetextview, imageswitcher, and textswitcher for specific scenarios.

The available layout includes linear layout linearlayout, framework layout framelayout, relativelayout, and others. For more examples, see common layout objects.

If these predefined components or la s cannot meet your needs, you can create your own view class. If you only need to adjust the existing widget or layout, you only need to subclass the widget or layout and override it.

Creating your own view subclass allows you to precisely control the shape and functions of the interface elements. To give a general impression on this kind of control, the following are some examples to illustrate what you can do with them:

· You can create a fully custom view type, such as a volume control knob drawn using a 2D image, to make it look like a simulated electronics.

· You can combine a group of view components into a separate component, maybe like a combo box (a combination of the pop-up list and free-input text segments ), A two-pane selector control (A left pane and a right pane each have a list, you can choose which item should be in which list), and so on.

· You can rewrite the rendering method for editing the text edittext component (this method is used in Notepad tutorial in the notepad guide to create a striped notepad page effect ).

· You can capture other events, such as buttons, and then process them in a custom manner. (Like what a game does)

The following sections explain how to create custom views and use them in your applications. For more information, see View class.

Back directoryBasic method the basic approach

The following is an overview of how to start creating a custom view component:

1. Extend an existing View class and subclass it.

2. Override some methods in the parent class. These methods start with "on", such as ondraw (), onmeasure (), and onkeydown (). This is used to override the on... The event is similar.

3. Use your new extension class. After these steps are completed, your extension class can replace the basic view.

Tip:Extension classes can be defined as internal classes that use their activities. In this way, activities can control access to them, which is useful but not necessary (maybe you want to create a wider public view in the application ).

Back directoryFull custom component fully customized components

Custom components can be used to create the graphical components you want. Maybe a graphic vu looks like an old-fashioned analog metering device, or a chorus subtitle with a bullet ball moving with the text so that you can sing on a karaoke machine. Either way, what you want is impossible to accomplish by built-in components, no matter how you combine them.

Fortunately, you can simply create components as you wish, unless you don't think of them, or limited by the screen size and available power (Remember, in the end, your application must run on a device that has much less power than the desktop workstation ).

To create a fully custom component:

1. No surprise. The most common view you can extend is the view. Therefore, you usually create your super component by extending it.

2. you can supply a constructor to read attributes and parameters from XML, or you can consume your own attributes and parameters (maybe the color and range of the vuvutable, or the width and damping of the pointer,)

3. You may also want to create your own event listeners, attribute access and modifiers in your components, and other actions that may be more complex.

4. You will almost certainly need to rewrite onmeasure (), and it is also likely that you need to rewrite ondraw (). If you want this component to display something. Both have default behaviors. The default ondraw () method does not do anything, and the default onmeasure () method always sets a size of X-this may not be what you want.

5. Other Methods on... can also be rewritten as required.

Back directoryExtends ondraw () and onmeasure () Extend ondraw () and onmeasure ()

The ondraw () method is used to pass you a canvas object, on which you can implement anything you want: 2D graphics, other basic or custom components, style text, or anything else you can think.

Note:This is not applicable to 3D images. If you want to use 3D graphics, you must extend surfaceview instead of view and draw it from a separate thread. See the glsurfaceviewactivity example for more details ..

Onmeasure () will be used more. Onmeasure () is a key part of drawing conventions between your components and their containers. Onmeasure () should be rewritten to effectively and accurately report the size of the part it contains. However, due to some restrictive requirements of the parent class (passed to the onmeasure () method) and the requirements for calling the setmeasureddimension () method with width and height (once calculated, this will be a little more complicated. If you fail to call this method from an override onmeasure () method, an exception During measurement is returned.

In summary, the onmeasure () implementation looks as follows:

1. Given the width and height measurement specifications (widthmeasurespec and heightmeasurespec both represent the integer encoding of the dimension) to call the override onmeasure method, which should be regarded as a restrictive requirement on the measurement. The complete reference is in the view. onmeasure (INT, INT) document, which also describes the entire measurement operation ).

2. The onmeasure () method of your component should calculate a width and height to draw this component. It should be left in the range specified by the passed specification as much as possible, although it can choose to exceed them (in this case, the parent class can choose the processing method, including cropping, scrolling, and throwing an exception, or, you may require onmeasure () to try again and use different measurement specifications .)

3. Once the width and height are calculated, the setmeasureddimension (INT width, int height) method must be called based on the calculated measurement. If the call fails, an exception is thrown.

The following is a summary of some other basic methods called by the framework on the View:

CATEGORY category Method Methods Description
Create Constructor One form of constructor is called when a view is created from the code, and the other is called when the view is expanded from a layout file. The second form should parse and apply any attributes defined in the layout file.
Create Onfinishinflate () Called when a view and all its sub-items have been expanded in XML.
Layout Onmeasure (INT, INT) Used to determine the size requirements of the view and all its sub-items.
Layout Onlayout (Boolean, Int, INT) This view is called when a dimension and position should be assigned to all its sub-items.
Layout Onsizechanged (INT, Int, Int, INT) Called when the size of this view is changed.
Painting Ondraw (canvas) Called when the view needs to draw its content.
Event Processing Onkeydown (INT, keyevent) Called when a key event occurs.
Event Processing Onkeyup (INT, keyevent) This API is called when a key release event occurs.
Event Processing Ontrackballevent (motionevent) Called when a ball tracking event occurs.
Event Processing Ontouchevent (motionevent) Called when a touch screen action event occurs.
Focus Onfocuschanged (Boolean, Int, rect) Called when the view gets or loses focus.
Focus Onwindowfocuschanged (Boolean) Called when the window containing the view gets or loses the focus.
Attaching Onattachedtowindow () Called when a view is attached to a window.
Attaching Ondetachedfromwindow () Called when a view is split from a window.
Attaching Onwindowvisibilitychanged (INT) Called when the visibility of the window containing the view changes.
Back directoryExample of a custom view: a custom View Example

The customview example in API demos provides a demonstration of the custom view. This custom view is defined in the labelview class.

The labelview example illustrates many different aspects of a custom component:

· Extended View class for a fully custom component.

· The parameterized constructor uses view extension parameters (these parameters are defined in XML ). Some of them are passed to the view superclass, but more importantly, some custom attributes are used by labelview.

· Set the expected type of a label component, such as settext (), settextsize (), and settextcolor.

· An override onmeasure method is used to determine and set the drawing size of this component. (Note that in labelview, the actual work is completed through a private measurewidth () method .)

· An override ondraw () method to draw a label into the canvas provided. Method to draw the label onto the provided canvas.

You can refer to some examples in custom_view_1.xml. In particular, you can see a mix of Android: namespace parameters and custom app: namespace parameters. These apps: the parameters are recognized and used by labelview and defined in a formatable internal class of the r Resource class.

Back directoryCompound controls

If you do not want to create a fully custom component, but want to assemble a group of existing controls into a reusable component, you can create a composite component (or composite control) to meet the requirements. In a small container, some more atomic controls (or views) are integrated into a logical project group, which can be treated as a single control. For example, a combo box can be viewed as a single-line text editing control and a combination of adjacent buttons with pop-up lists. If you press this button and select items from the list, it will be generated to the text editing domain. However, you can also directly enter the items in the text editing domain if you want.

In Android, there are actually two other views that do the same: spinner and autocompletetextview. However, the concept of a combo is easier to understand.

To create a composite component:

1. Generally, the starting point is a certain type of layout. Therefore, a class is created to expand the layout. In the case of a combo box, we may use a horizontal linear layout of linearlayout. Remember that other la s can be nested in it, so that this composite component can be complex and structured at will. Note that it is like a view. You can use the Declaration (XML-based) method to create the contained components, or embed them in the program by encoding.

2. In the constructor of this new class, any parameters expected by the super class are used and passed to the super class constructor first. Then you can create other views for the new component. This is where you will create the edittext field and popuplist. Note that you may also need to introduce your own attributes and parameters to XML, which will be extracted and used by your constructor.

3. you can also create a listener for the events that may be generated by the included view. For example, you can click the listener Method for a list item, it is used to update the content of the corresponding text edit box when a list item is selected.

4. You may also want to create your own features by accessing and modifying functions. For example, the edittext value can be initialized and queried as needed.

5. When extending a layout, you do not need to override the ondraw () and onmeasure () methods, because the layout will have default behavior. However, you can rewrite them as needed.

6. You may rewrite other on... methods, such as onkeydown (). When a specific key is pressed, a specific default value may be selected from the pop-up list.

In short, creating custom controls based on layout has the following benefits:

· You can specify the layout using declarative XML like an active screen, or implement view nesting through programming.

· Ondraw () and onmeasure () methods (plus most other on... methods) may have appropriate behavior, so you do not need to override them.

· Finally, you can quickly build complex composite views and reuse them as a single component.

Example of composite controls examples of compound controls

In the API demos Project released with the SDK, there are two list examples-Example 4 and Example 6. Under views/lists, a speechview expanded from a linear layout is demonstrated, this component is used to show the excerpt of a speech. The corresponding classes are in list4.java and list6.java.

Back directoryModify an existing view type modifying an existing view type

In some cases, there are simpler and more practical methods to create custom views. If there is a view that is very similar to what you want, you only need to extend and override the relevant behavior methods on this component. You can certainly do anything through fully customized components, but you can also do many things to meet your needs through a specific class in a view hierarchy chart.

For example, the SDK contains a notepad application. This program demonstrates many aspects of the Android platform application, one of which is to expand an edittext view to create a striped notepad. This is not a perfect example. The APIs used may change, but it does illustrate the principle.

If you have not done so, import the notepad example to eclipse. In particular, let's take a look at the definition of myedittext in the noteeditor. Java file.

The following are some notes:

1. Define the definition

This class is defined in the following code lines:

Public static class myedittext extends edittext

O it is defined as the internal class of the noteeditor activity, but it is public, so it can be accessed outside the noteeditor class by using noteeditor. myedittext.

O it is static, which means it does not generate a so-called "pseudo method" that allows it to access data from the parent class ", this means that its behavior is more like an independent class than it is strongly associated with noteeditor. This is a concise method for creating internal classes. If these classes do not need to be accessed from external classes, this makes the generated classes small and easy to use by other classes.

O it extends edittext. We choose to customize components based on this view. After these ends, the new class can be used to replace the General edittext view.

2. class initialization

Generally, superclasses are called first. In addition, this is not the default constructor, but a parameterized constructor. This edittext is created by extending these parameters in the XML layout file. In this way, our constructors also need to use them and pass them to the superclass constructor.

3. Override method overridden Methods

In this example, only one method needs to be rewritten: ondraw ()-but when creating your own component, you may need to override other methods.

For the notepad example in notepad, the override ondraw () method allows us to draw the Blue Line on the edittext view canvas (this canvas is passed to the override ondraw () method ). This super. ondraw () method is called before the end of this method. This superclass method should be called, but in this example, it is called after the line is drawn.

4. Use the custom component

Now we have a custom component, but how can we use it? In the notepad example of notepad, this custom component is directly used in the layout Declaration, so let's take a look at the note_editor.xml file under the Res/layout directory.

Copy to clipboardXML/html code
  1. <View
  2. Class = "com. Android. notepad. noteeditor $ myedittext"
  3. Id = "@ + ID/Note"
  4. Android: layout_width = "fill_parent"
  5. Android: layout_height = "fill_parent"
  6. Android: Background = "@ Android: drawable/empty"
  7. Android: padding = "10dip"
  8. Android: scrollbars = "vertical"
  9. Android: fadingedge = "vertical"/>

This custom component is created in XML in a common view, and this class is specified by the full package name. We also need to note that the internal class we defined is referenced by the noteeditor $ myedittext mark, which is a standard way to reference the internal class in Java programming language.

If your custom view component is not defined as an internal class, you can use an XML element name to declare the view component and do not need to include the class attribute. For example:

Copy to clipboardXML/html code
  1. <Com. Android. notepad. myedittext
  2. Id = "@ + ID/Note"
  3. .../>

Note that the myedittext class is now an independent class file. This technology is ineffective when this class is embedded in the noteeditor class.

Other attributes and parameters in the definition are passed to the constructor of the custom component and then to the constructor of edittext. Therefore, these parameters are the same as those used for the edittext view. Note that you can also add your own parameters, which will be discussed below.

This is all the content. I admit that this is just a simple example, but the key is-the complexity of creating a custom component is only related to your needs.

A more complex component can rewrite more on... methods and introduce some of its own helper methods to customize its features and behaviors. The only limit lies in your imagination and what you want this component to do.

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.