Android API Guides---Custom components

Source: Internet
Author: User

Custom components

Android provides a complex and powerful modular model for building your user interface based on basic layout classes: viewing and ViewGroup. Called widgets and layouts, respectively-first, the platform includes a variety of pre-built ViewGroup subclasses that you can use to build your UI.
Some of the available widgets list includeButtonTextView,EditTextListViewCheckBoxRadioButtonGallery,Spinner, and multiple dedicated autocompletetextview,imageswitcher and Textwatcher.
The linearlayout of the available layouts, the framelayout,relativelayout, and so on. For more examples, see Common layout objects.
If you do not have a predefined part or layout that meets your needs, you can create your own view subclasses. If you only need to make small adjustments to an existing part or layout, you can simply inherit the widget or layout and overwrite it with the method.
Create your own child views to give you precise control over the appearance and functionality of your screen elements. To let you customize the view to get control of the idea, here are some examples of what you can do with them:
You can create a fully customizable render view type, such as the volume control knob using 2D Graphics rendering, and it resembles an analog electronic control.
You can combine a set of view components into a new single ingredient, perhaps to make a selection of controls like a ComboBox, a double pane (left, right pane, in the list (pop-up list, and can enter a combination of text fields for free) each time there you can reassign the item in which list, and so on.
You can overlay a edittext component on the screen to render the way (Notepad tutorial uses this effect well, creating a shady, Notepad page).
You can capture other events, such as keystrokes, and handle them in some custom ways (such as games).
The following sections explain how to create custom views and use them in your application. For detailed reference information, see the class.
Its basic approach
Here's what you need to know to create your own view components to start with:
Extend an existing view class or subclass with your own class.
Some methods that overwrite from the superclass. These superclass methods rewrite the start with "on", for example, the OnDraw (), Onmeasure (), and the onkeydown (). This is similar to the above ... Event activity or listactivity you cover the life cycle and other functional hooks.
Use the new extension class. Once completed, the new extension class is used instead of the view on which it is based.
Tip: Extension classes can be defined as inner classes within the activity in which they are used. This is useful because it controls access to them, but it is not necessary (perhaps you want to create a wider use of the new public view in your application).
Fully customizable components
A fully customizable component can be used to create a graphical component that you want to appear. Maybe a graphical vu meter that looks like an old analog meter, or bounces the ball along the move, so you can sing it with a karaoke machine to a long text view. Either way, what you want, built-in components don't work, no matter how you combine them.
Fortunately, you can easily create, look and act on any ingredient that you like, perhaps only your imagination, the size of the screen and the processing power available (keep in mind that ultimately your application may need to run with significantly less power than your desktop workstation).
To create a fully customized component:
You can extend the most common view that is, undoubtedly, the landscape, so you will typically start by extending this creation of new super components.
can provide a construct that can take properties and parameters from XML, and can also consume its own such properties and parameters (possible color and range of vu table, or width and needle damping etc.)
You might want to create your own event listeners in your component class, Access and modify properties, and possibly more complex behavior as well.
You will almost certainly want to overwrite onmeasure (), and there may also be a need to rewrite the OnDraw () if you want the component to display something. While both have default behavior, the default OnDraw () will do what, and the default onmeasure () will always set the size to 100x100-which may not be what you want.
The other way ... can also be overwritten as needed.
Extended OnDraw () and Onmeasure ()
The OnDraw () method provides you with a canvas on which you can implement anything you want: 2D graphics, other standard or custom components, style text, or whatever else you can think of.
Note: This does not apply to 3D graphics. If you want to use 3D graphics, you have to extend surfaceview instead of views, drawing from a single thread. Please refer to the Glsurfaceviewactivity sample for details.
Onmeasure () is a little more involved. Onmeasure () is a key part of the contract rendering between your component and its container. Onmeasure () should be rewritten, efficiently and accurately reporting the measurements of its included parts. This is slightly more complicated by limiting the requirements from the parent (which is passed to the Onmeasure () method) and by the requirement that once the Setmeasureddimension () method has been computed calls the width and height of the measurement. If the method cannot be called from an overridden Onmeasure () method, the result will be to measure the time of the exception.
At a higher level, the implementation of Onmeasure () looks like this:
The overridden Onmeasure () method is called, the width and height of the metric specification (both the Widthmeasurespec and the Heightmeasurespec parameters, regardless of the size of the integer code), and it should be considered as corresponding to the requirement to produce a limit on the width and height of the measured value. A complete reference sample of these specifications can be limited and can be found in the reference document View.onmeasure (Int,int) (not explained in this reference document, as well as a good job of the entire measurement operation).
The Onmeasure () method of the component should calculate the width and height of the measurement, which will require rendering the component. It should try to stay within the incoming specification, although it can choose to exceed them (in this case, parents can choose what to do, including cutting, scrolling, throwing an exception, or asking Onmeasure () to try again, perhaps with different measurement specifications).
Once the width and height are computed, the setmeasureddimension (int width, interpretation height) method must be called with the calculated measurement result. If you do not do this will cause an exception to be thrown.
The following is a summary of some of the framework's comments calling for other standard methods:

category methods description
creation constructors there is a form of the of the constructor that was called when the view was created from code and a form That was called when the view was inflated from a layout file. The second form should parse and apply any attributes defined in the layout file.
onFinishInflate() Called after a view and all of its children have been inflated from XML.
Layout onMeasure(int, int) Called to determine the size requirements for this view and all of its children.
onLayout(boolean, int, int, int, int) Called when the This view should assign a size and position to all of its children.
onSizeChanged(int, int, int, int) Called when the size of this view has changed.
Drawing onDraw(Canvas) Called when the view should to render its content.
Event processing onKeyDown(int, KeyEvent) Called when a new key event occurs.
onKeyUp(int, KeyEvent) Called when a key up event occurs.
onTrackballEvent(MotionEvent) Called when a trackball motion event occurs.
onTouchEvent(MotionEvent) Called when a touch screen motion event occurs.
Focus onFocusChanged(boolean, int, Rect) Called when the view gains or loses focus.
onWindowFocusChanged(boolean) Called when the window containing the view gains or loses focus.
Attaching onAttachedToWindow() Called when the view was attached to a window.
onDetachedFromWindow() Called when the view was detached from its window.
onWindowVisibilityChanged(int) Called when the visibility of the window containing the view had changed.
Custom View Example


The CustomView sample in the API demo provides an example of a custom view. Custom views are defined in the Labelview class.


The Labelview example demonstrates different aspects of a custom component:


The extended view class fully customizes the component.
Parameter constructors, which consider the parameters of inflation (parameters defined in XML). Some of them pass to the view over the past, but more importantly, there are definitions, and are used to labelview some custom properties.
The type of standard public method that you want to see is a label component such as SetText (), Settextsize (), SetTextColor (), and so on.
An overriding Onmeasure method to determine and set the rendering size of the component. (Note that in Labelview, the real work is done by the private Measurewidth () method.) )
An overridden OnDraw () method to draw on the label provided on the canvas.
You can see some usage examples of Labelview custom views in custom_view_1.xml from the sample. In particular, you can see the mix of the two robots: named parameters and Custom applications: namespace parameters. These applications: The parameters are the Labelview identified and customized with the work, and in the sample inside the set style inner class r defines the resource definition class.


Composite controls


If you do not want to create a fully customizable component, but are looking to put together a set of existing controls and then create a compound component (or compound control), a reusable component may fit the bill. Simply put, this brings together a group of multiple atomic controls (or views) converted into logical groups that can be viewed as a single thing item. For example, a combo box can be thought of as a single line of EditText fields and adjacent buttons with an additional popuplist combination. If you press the button from the list, select something that fills the EditText field, but the user can also enter something directly into the edittext if they wish.


In Android, there are actually two other comments readily available to do this: fine tuning and Autocompletetextview, but anyway, the concept of a combo box makes an easy-to-understand example.


To create a composite component:


The usual starting point is some form of layout in order to create a class that extends the layout. Perhaps in the case of a combo box, we may use the linearlayout in the horizontal direction. Keep in mind that other layouts can be nested inside, so the compound composition can be arbitrarily complex and structured. Note that just as you treat an activity, you can use a declarative (XML-based) way to create a contained component, or you can nest these programmatically from your code.
In the constructor for the new class, take any parameters that are super-expected and pass through the construction of their parent class first. You can then set up additional comments that are used in your new component, which is the EditText farm and popuplist that you will create. Note that you may also introduce your own attributes and parameters into the XML that can be pulled out and used in the constructor.
You can also create your comments on the contents of the edittext that may generate events such as listeners, listener for list items, click Listener If the list makes a selection update.
It is also possible to create your own properties with access and modification, for example, to allow the EditText value to be initially set on the component and query its contents when needed.
In the case of extended layouts, you do not need to rewrite the OnDraw () and Onmeasure () methods, because the layout will have default behavior that might work well. However, you can still overwrite them if you need to.
You may be covered by other ... method, such as onkeydown (), may select some default values by pressing a key from the pop-up list of the combo box.
In summary, using layouts as the basis for custom control has many advantages, including:


You can use the declared XML file, just like with the activity to specify the layout of the screen, or you can programmatically create views and nest them into your code layout.
The OnDraw () and Onmeasure () methods (plus ... Methods most of the others) might have the appropriate behavior, so you don't have to overwrite them.
Finally, you can build arbitrarily complex compounds very quickly, and view them as if they were a single ingredient to reuse them.
Examples of composite controls


In the accompanying SDK API demo project, there are two example lists-Example 4 below to see Example 6/list show extension linearlayout do a component to display the Speechview in the voice quotes. The class that corresponds to the sample code is List4.java and List6.java.


Modify an existing view type


Not being used to create custom views is useful in some cases an easier choice. If there are already very similar to what components you want, you can simply extend the component and just overwrite the behavior you want to change. You can do all the things you want to do with a completely custom component, but if you start with a more professional class at the view level, you can also get a lot of freedom of behavior which may not be exactly what you want.


For example, the SDK includes samples in the Notepad application. This shows many aspects of using the Android platform, which is extending a edittext view to make the liner Notepad. This is not a perfect example of the API that might be changed from this early preview, but it does show the principle.


If you haven't done so, import a Notepad sample to eclipse (or just look at the source using the provided link). Define a specific appearance in the Noteeditor.java file Myedittext.


Here are some things to note


Defined
The following line of the class definition:
EditText of public static class Myedittext extension
It is defined as an inner class within the noteeditor activity, but it is public so that it can be accessed as Noteeditor.myedittext from the Noteeditor class, if needed.
It is static, which means that it does not produce so-called "synthetic methods" that allow it to be accessed from the parent class, which in turn means that it does behave as a separate class rather than some closely related noteeditor access data. This is the way to create inner classes if they do not need to access the state from the external class in a clean manner, keep the generated class small, and allow it to be easily used from other classes.
It expands the EditText, which is also our choice in this case to customize the view. When we are done, the new class will be able to replace a normal edittext diagram.
Initialization of the class
As always, super is called first. Moreover, this is not a default constructor, but one of the parameters. The edittext with these parameters is created when it expands from an XML layout file, so our constructors need to be taken by both parties and passed to the parent class as well.
Override method
In this example, only one method is overwritten: OnDraw (-but it can be easily created in your own custom components that others need.)
For Notepad samples, the overlay OnDraw () method allows us to draw the Blue line on the EditText view canvas (the canvas is passed to the overloaded OnDraw () method). The Super.ondraw () method is called before the method ends. The superclass method should be called, but in this case we do at the end, we have painted the rows we want to include.
Working with custom components
Now that we have our custom components, but how do we use it? In the Notepad example, the custom component is laid out directly from the declaration, so see Note_editor.xml in the RES/Layout folder.

<view  class="Com.android.notepad.noteeditor$myedittext"   ID="@+id/note"  Android:layout_width="Fill_parent"  Android:layout_height="Fill_parent"  Android:background="@android:d rawable/empty"  android:padding="10dip"  Android:scrollbars="Vertical"  Android:fadingedge="Vertical" />
The custom component is created as a generic view in XML and uses the class specified in the complete package. Also note that the inner class that we define is the standard way to use the instructions to edit the reference $ my edittext notation refers to the internal class Java programming language.
If your custom view component is not defined as an inner class, then you can, in addition, declare the XML element name of the view component and exclude the class attribute. For example:

<com.android.notepad.myedittextid="@+id/note"/> 
Please note that the EditText class is now a separate class file. This technique will not work properly when the class is nested in the comment editor class.
Other properties and parameters in the definition are passed to the custom component construct, and then passed on to the constructed edittext, so they are the same parameters that you want to use with a edittext view. Note that it can add its own parameters as well, and we'll touch that again below.
And all this is so simple. Admittedly, this is a simple example, but this-creating a custom component can only be as complex as you need it.
More complex ingredients may be more ... Covered methods, and introduced some of their own helper methods, greatly customizing their properties and behavior. The only limitation is your imagination, what you need to do with the components.


Android API Guides---Custom components

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.