Creating custom components

Source: Internet
Author: User

Custom Components
The Android system provides a powerful component model for users to create their own UIS. This model is based on basic layout classes such as View and ViewGroup. The Android system contains the pre-created child classes of View and ViewGroup-widgets and layouts-you can use these child classes to build your own UI, at the beginning of Android development, we used these systems. However, as the project needs, these basic UI components cannot meet our needs, in this case, we need to follow the component model to create custom UI components.
Widgets mainly includes the following parts: Button, TextView, EditView, ListView, CheckBox, RadioButton, Gallery, and Spinner. Of course, it also includes some special-purpose widgets: autoCompleteTextView, ImageSwitcher, and TextSwitcher.
Layouts mainly includes LinearLayout, FrameLayout, RelativeLayout, and others. For more examples, see Common Layout Objects.
When the existing components cannot meet the requirements, we need to create our own View subclass. If you only need to make small adjustments to the existing widget or layout, you can simply create a subclass of the widget or layout and overwrite the methods.
By creating a View subclass, You can precisely control the display and functions of each element on the screen. Some examples are listed here to illustrate how to control custom components:
* You can create a fully custom rendering View type. For example, you can use 2D graphics to render the volume control knob to make it look like a simulated power control.
* You can combine a group of View components to form a new single component, it may be like a ComboBox (which is composed of a popup list and a text without any entries), a dual-pane selection controller (each left and right has a panel, in addition, each panel has a list. You can change another pane by specifying the content in a pane, in fact, the first drop-down box in the frequently used weather forecast selects the province, and the second drop-down box will become the city included in the province. Now I understand it, huh, huh !) And so on.
* You can override the rendering method of the EditeText component on the screen (NotePad Tutorial uses this method to create a lined-notepad page ).
* You can capture other events, such as keys and handle them in a custom way (for example, in a game ).
The following explains how to create custom Views and use this custom component in an application. For detailed reference information, see View class.
 
Basic Method
To create a custom View component, you must know the following content:
1. Let your class inherit the existing View class or View subclass.
2. Some methods that overwrite the superclass. The superclasses to be overwritten start with "on", for example, onDraw (), ONMeasure (), and onKeyDown (). This is a bit similar to the on... events of Acitivity or ListActivity. you overwrite these methods (on... events) for their lifecycles and other functions ).
3. Use the new extension class. Once completed, you can use the custom extension class where you can use the base class.
Tip: the extension class can be defined as an internal class in the activities of the extension class to be used. This is not necessary, but it is very useful because it controls the permission to use extended classes.
Fully custom components
A Fully customized component can be used to create a graphical component to be displayed anywhere you want. It may be a graphic VU meter that looks like an old analog meter, or a long text box with a forward ball. The ball moves with characters so that you can sing with a karaoke machine. Also, you need to do some things, but no matter how you combine existing components, you cannot achieve the desired effect (in this case, you need to completely customize the components ).
Fortunately, you can easily create components that suit your needs for style and functionality. The only factor you need is your imagination, screen size, and available power (Remember, your applications usually run on devices that are much less powered than the desktop environment ).
Create a fully custom component:
1. There is no doubt that the most often inherited View is. Therefore, you generally inherit this class to implement custom build;
2. You can provide a constructor to obtain and parse attributes and their parameters from the XML file, in addition, you can customize attributes and parameters (which may be the color and value range of the vuvutable or the width of the noodles );
3. You may want to create your own event listeners, accessors (accessors) and modifiers (modifiers) of attributes, or other more complex actions.
4. If you want to display some things through custom components, you almost always need to overwrite onMeasure () and often need to overwrite onDraw (). Both of the above include the default action. The default action of onDraw () is not to perform any action, onMeasure () the default action is to set the display size to 100X100 ---- and this default size may not be what you want (size ).
5. Other Methods on... must also be overwritten when needed.
Extends onDraw () and onMeasure ()
The onDraw () method passes a Canvas to you. You can complete the desired effect on the Canvas: 2D graphics, other standard or custom components, styled text, or anything else you want.
Note: This cannot be used to complete 3D images. If you want to use 3D graphics, you must extend SurfaceView to replace the View and complete the painting in an independent process. For details, you can view the GLSurfaceViewActivity example.
OnMeasure () involves more. onMeasure () is a very strict part of the custom component and rendering contract between the containers that contain it. OnMeasure () must be overwritten to report the size of the part it contains very efficiently and accurately. The limitations from the parent component (the part passed into the onMeasure method) and the call to the setMeasureDimension () method through the measurement size will make this a little complicated. If you fail to call this method (setMeasureDimension () from an override onMeasure () method, an exception will occur during measurement.
At a higher level, onMeasure () is implemented as follows:
1. The override onMeasure () method is called along with the width and height measurement specification (widthMeasureSpec and heightMeasureSpec parameters, both representing the size of the integer. For a complete reference to the types of restrictions that can be obtained by these specifications, see View. onMeasure (int, int) is found in this document (this reference document provides a better explanation of the complete measurement operation ).
2. The onMeasure () method of your custom component must calculate a width and height value, which are used to render the component. These two values must be within the passed measurement specification, although they can be expanded (the width and height values) (in this case, the parent component can choose how to handle: this includes the ability to flip, scroll, throw a field, or allow onMeasure () to retry with different measurement specifications ).
3. Once the width and height are calculated, the calculated values must be used as parameters to call the setMeasureDimension (int width, int height) method. If this operation fails, an exception is thrown.
The following is a summary of the standard methods called by the application framework in views, for example:



Example of a custom View
The M View Example provided in API Demos is a good example for creating a Custom View. In the Custom View Example, the Custom View is defined in the class LabelView.
LabelView shows many different aspects of a custom component:
* Create a fully custom component by extending the View class;
* The parameterized constructor allows you to parse parameters (the parameters are defined in the XML file ). Some of the parameters are passed to the View base class, but more importantly, some custom attributes are defined for the LabelView component in this example.
* Standard public methods of the label component type are used, such as setText (), setTextSize (), and setTextColor.
* Use the override onDraw () method to draw the label on the provided canvas.
You can see some examples of LabelView usage in the custom_view_1.xml file. Specifically, you will see that the android: namespace parameter and the custom app: namespace parameter are used in combination. LabelView can recognize these apps: parameters and work well. These parameters are defined in a styleable internal class of the example R resource definition class.
<! -- Demonstrates defining custom views in a layout file. -->
 
 
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Xmlns: app = "http://schemas.android.com/apk/res/com.example.android.apis"
Android: orientation = "vertical"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content">
 
 
<Com. example. android. apis. view. LabelView
Android: background = "@ drawable/red"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
App: text = "Red"/>
 
 
<Com. example. android. apis. view. LabelView
Android: background = "@ drawable/blue"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
App: text = "Blue" app: textSize = "20dp"/>
 
 
<Com. example. android. apis. view. LabelView
Android: background = "@ drawable/green"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
App: text = "Green" app: textColor = "# ffffffff"/>
 
 
</LinearLayout>
<! -- Demonstrates defining custom views in a layout file. -->


<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Xmlns: app = "http://schemas.android.com/apk/res/com.example.android.apis"
Android: orientation = "vertical"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content">


<Com. example. android. apis. view. LabelView
Android: background = "@ drawable/red"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
App: text = "Red"/>


<Com. example. android. apis. view. LabelView
Android: background = "@ drawable/blue"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
App: text = "Blue" app: textSize = "20dp"/>


<Com. example. android. apis. view. LabelView
Android: background = "@ drawable/green"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
App: text = "Green" app: textColor = "# ffffffff"/>


</LinearLayout> combination control
If you do not want to create a fully custom component, but want to combine existing components in a group, you should create a composite component (or composite control ), to meet the requirements. In summary, a group of parts is logically put together and then operated as a whole. For example, a Combo Box can be composed of a single row of EditText and a button with PopupList. If you press the button and select an item from the list, the selected item will fill the EditText, but if you want, they can also manually enter the content in EditText instead of selecting from the list.
In the Android system, two other components have been provided to accomplish this: Spinner and AutoCompleteTextView. However, it is easier to use a Combo Box as an example.
To create a composite component:
1. Generally, it starts with a Layout. Therefore, you can create a class extension and a Layout. In the Combo Box example above, we can extend a horizontally placed LinearLayout. Remember that other layouts can be nested in it, so the composite components can be constructed and complex. Note: Just like an Activity, you can create contained components through the XML file class or implement layout through encoding.
2. In the constructor of the new class, the constructor receives any parameters that the base class can receive and first passes them to the constructor of the base class. In this way, you can use other components in your own components. Here you can create EditText and PopupList. Note: You can also define your own attributes and parameters in the XML file. These parameters can be used by your constructor.
3. If the components you include can generate events, you can also create event listeners for these events. For example, you can set an event listener for a selected list item to update the EditText content.
4. You can also define attributes for accessors (accessors) and modifiers (modifiers). For example, you can specify an initial value for EditText in a component, you can query its value as needed.
5. When extending a Layout, you do not need to overwrite the onDraw () and onMeasure () methods. Because layout already contains the default behavior, it can work properly. However, you can overwrite them if needed.
6. You can also overwrite other .. for example, onKeyDown (). When a specific key is pressed, you can select a default value from the popup list of a combo box.
To sum up, Layout has a series of advantages as the basis of Custom Control, including:
* You can use an XML file like an Activity to define the layout, or use encoding to implement the layout.
* OnDraw () and onMeasure () methods (most Methods Starting with on ..) will have appropriate actions, so you don't have to overwrite them.
* Finally, you can quickly build any complex components and reuse them as one component.
Example of combined control:
The API Dmeos released with the SDK contains two List examples-Example4 and Example6 in Views/Lists, which show a SpeechView extended from LinearLayout to display Speech quotes. The corresponding classes are included in List4.java and List6.java of the sample code.
Modify an existing View type
In special environments, there is also a very simple method for creating custom views. If you already have a component that is very similar to the one you want, you can simply expand the component and only cover what you want to change. You can create a fully custom component to complete all these tasks. However, if you start with a special class that exists in the View hierarchy, you can get a lot of results you may want, which greatly reduces your workload.
For example, the SDK contains a NotePad sample application. This application demonstrates many features of the Android platform. In this example, you can create a lined notepad by extending an EditText View. This is not a particularly appropriate example. The APIs used to complete this operation may have been changed as the system version changes, but it is sufficient to demonstrate the principles in the future.
If you do not, import the NotePad example to Eclipse (or view the source file through the link provided below ). In particular, take a closer look at the MyEditText defined in the NoteEditor. java file.
Note the following:
1. Definition:
This class is defined as follows:
Public static class MyEditText extends EditText
* It is defined as an internal class of NoteEditor, but its access permission is public. Therefore, you can use this class outside the NoteEditor class through NoteEditor. MyEditText.
* This class is also static, meaning it does not need to generate the so-called "synthetic methods" that allows the parent class to operate data ", this also means that it is an independent class rather than a class strongly associated with NoteEditor. If they do not need to obtain the status from external classes, this is a clean method for creating internal classes to ensure that the generated classes are very small, and can be easily used in other classes.
* It inherits from EditText. Here we select it for custom View. After the custom work is completed, this new class can replace the normal EditText.
2. class initialization:
As usual, superclasses are called first. However, this is not the default constructor, but the constructor that contains a parameter. EditText is created by parsing these parameters from the XML layout file. Therefore, our constructor needs to receive these parameters and pass them to the super class constructor.
3. Methods covered:
In this example, there is only one method to be overwritten: onDraw () ---- however, when you need it, you can also easily overwrite other methods to create custom components.
In the NotePad example, the override onDraw () method allows us to draw a green line on the canvas of the EditText view (the canvas passed into the onDraw () method. Before this method is completed, we need to use the super. onDraw () method. The superclass method should be called, but in this case, we call this method after we finish drawing the part we want to include.
4. Use custom components:
At this point, we have completed the custom component, but how can we use this custom component? In the NotePad example, we use it directly in the layout file. So let's take a look at the note_editor.xml file under the res/layout directory:
<View
Class = "com. android. notepad. NoteEditor $ MyEditText"
Id = "@ + id/note"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: background = "@ android: drawable/empty"
Android: padding = "10dip"
Android: scrollbars = "vertical"
Android: fadingEdge = "vertical"/>
<View
Class = "com. android. notepad. NoteEditor $ MyEditText"
Id = "@ + id/note"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: background = "@ android: drawable/empty"
Android: padding = "10dip"
Android: scrollbars = "vertical"
Android: fadingEdge = "vertical"/> * a custom component is created in an XML file as a general component, and the custom component class is specified by the complete package name. Note: We use the NoteEditor $ MyEditText symbol to reference internal classes. This is a standard method for using internal classes in JAVA.
If your custom component is not defined as an internal class, you can also declare the custom View component by using the name of the XML Element (but removing the class attribute, for example:
<Com. android. notepad. MyEditText
Id = "@ + id/note"
.../>
<Com. android. notepad. MyEditText
Id = "@ + id/note"
.../> Note that the MyEditText class is a separate class file. When this class is nested in the NoteEditor class, this technology will not work, so it must be a separate file.
* Other attributes and parameters in the definition are passed to the custom constructor and then to the EditText constructor. Therefore, they are the same as the parameters you use EditText. Note: You can also add your own parameters, which will be described below.
This is all the content. It is a simple task, but it is very important to create custom components based on your own needs (to meet your needs, you do not need to create custom components that are too complex ).
A more powerful component may need to overwrite Methods Starting with on... and introduce some of its own methods to implement custom attribute actions. The only limit is your imagination and the work you need for this component group.

From the column chenlong12580

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.