Custom components-games and Applications

Source: Internet
Author: User

If you should be good enough, Look At This http://www.gfan.com/dev/android/guide/topics/ui/custom-components.html, the official website is really powerful

In Android, your applications have a fixed connection with the view components, such as buttons, textviews, and edittext ), list box (listview), check box (checkbox), single button (radiobutton), scroll bar (Gallery), spinner ),
There are also some advanced view components with special purposes, such as autocompletetextview, imageswitcher, and textswitcher. In addition, a wide range of linear layout (linearlayout), Framework layout (framelayout ),
Such layout components are also considered view components, which are derived from the View class.

Your application displays these control components and layout components on the screen in a certain way. Generally, these components are enough for you, however, you should also know that you can use class inheritance to create your own components. Generally, You can inherit components such as view and layouts (layout components, it can even be some advanced control components. Next we will explain why inheritance is required:

  • You can create a completely custom component to implement a certain function. For example, you can use a two-dimensional Graphic creation control component to implement sound control, just like electronic control.
  • You can combine several components to form a new component. Your component may contain both ComboBox (a list of input texts) and dual-pane selector control (left and right list windows, you can allocate the subordination of each item in the window.
  • You can create your own layout component (layout ). The layout component in the SDK provides a series of options for you to build your own applications, however, senior developers will find it necessary to develop new layout components based on existing layout components, or even completely develop new components from the underlying layer.
  • You can overwrite the display or function of an existing component. For example, you can change the display mode of the edittext (editable text) component on the screen (refer to the notepad example to learn how to create an underline display page ).
  • You can capture events like pressing keys and handle them in some common ways (a game example ).

To achieve a certain goal, you may need to expand an existing view component. The following examples are used to teach you how to do this.

Content:
Basic method (the basic approach)
Full custom components (fully customized components)
Example of custom components (customized component example)
Component mixing (or control class mixing) (Compound components (or compound controls ))
Modify existing components (tweaking an existing component)
Summary (go forth and componentize)

Basic method (the basic approach)

The following steps are summarized to teach you how to create your own components:

  1. Let your class inherit an existing View class or view subclass.
  2. Methods to overload the parent class: the method of the parent class to be overloaded is generally'on', Such as ondraw (), onmeasure (), and onkeydown.
    • This is also applicable to activity or listactivity derivation. You need to reload some lifecycle functions and some other functional hook functions.
  3. Use your inheritance class: Once your inheritance class is created, you can use your inheritance class where the base class can be used, but the completion function is compiled by yourself.

The inheritance class can be defined in activities so that you can conveniently call it, but this is not necessary (maybe you want to create a component that everyone can use in your application ).

Full custom components (fully customized components)

A Fully customized component can be used to create graphical components for display. It may be a graphical meter like a voltmeter, or a ball that shows the lyrics in karaoke will scroll with music. In either way, you cannot simply use the combination of components, no matter how you combine these existing components.

Fortunately, you can easily create your own components as required, you will find that your imagination, screen size, and processor performance are insufficient (remember that your application will only run on platforms with lower performance than your desktop ).

The following describes how to create a fully custom component:

  1. The parent class of the most common view class is undoubtedly the View class. Therefore, you must create a subclass based on this class at first.
  2. You can write a constructor to extract attributes and parameters from the XML file. Of course, you can also define these attributes and parameters by yourself (maybe the color and size of the graphic measuring tool, or the width and amplitude of the pointer)
  3. You may need to write your own event listener, attribute access and modify functions, and some code on the functions of some components.
  4. If you want the component to display something, you are likely to overloadonMeasure()Function, so you have to reloadonDraw()Function. When both functions use the default oneonDraw() The function will not do anything, and the defaultonMeasure()The function automatically sets a 100x100-size, which may not be what you want.
  5. Otheron...All functions must be rewritten once.
onDraw()And onMeasure()

onDraw()The function will pass you a canvas object, through which you can do anything on a two-dimensional graph, including some other standard and common components and text formats, anything you can think of can be implemented through it.

Note:This does not include 3D graphics. If you want to use 3D graphics, you should change your parent class from view to surfaceview class and use a separate thread. See glsurfaceviewactivity
.

onMeasure()Functions are tricky, because this function is a key part of the interaction between components and containers,Onmeasure ()It should be reloaded so that it can effectively and accurately express the measured values of the part it contains. This is a bit complicated, because we should not only consider the restrictions of the parent class (throughOnmeasure ()). At the same time, we should know that once the width and height of the measurement come out, it should be called immediately.Setmeasureddimension ()Method.

To sum up, executeonMeasure()Functions are divided into several stages:

  1. ReloadonMeasure()The method is called, and the height and width parameters also involve (widthMeasureSpecAndheighMeasureSpecBoth parameters are Integer type), and you should consider the size limit of your product. For more information, see view. onmeasure (INT,
    INT) (the connection details the entire measurement operation ).
  2. Your component needs to passonMeasure()Calculate the necessary measurement length and width to display your component. It should be consistent with the specification, although it can implement features other than the specification (in this example, what can the parent class choose to do, including cutting, sliding, submitting exceptions, or calling again with different parameters?onMeasure()Function ).
  3. Once the height and width are calculated, you must callsetMeasuredDimension(int width, int height)Otherwise, an exception occurs.

Example of a custom component (a customized component example)

In API demos, customview provides an example of a custom component, which is defined in the labelview class.

The labelview example involves all aspects of custom components:

  • First, let the custom component be derived from the View class.
  • Compile a constructor with parameters (the parameters can come from an XML file ). Some of the above operations have been completed in the view parent class, but some custom components used by labelview have new parameters that need to be processed.
  • Some standard public functions, suchsetText(),setTextSize(),setTextColor()
  • Heavy LoadonMeasure()(Note: In labelview, a private function is used to determine the component size.measureWidth())
  • Heavy LoadonDraw()The function displays the lable on the provided canvas.

In this example, you can use custom_view_1.xml to view the usage of the custom component labelview. In XML files, note thatandroid:Andapp:Mixed use of two parameters,app:Parameters indicate that the application is considered an individual of the labelview component, which will also be defined as resources in the r class.

Compound components (or compound controls)

If you do not want to create a fully custom component, but a new component is generated by a combination of several existing components, hybrid component technology is more suitable. To put it simply, combining several existing components into a logical combination can be encapsulated into a new component. For example, a combo box component can be seen as a mixture of edittext and a button component with a pop-up list. If you click the button to select an item for the list,

In Android, there are actually two other view classes that can achieve similar effects: spinner and autocompletetextview, but combo
Box is easier to understand as an example.

The following describes how to create a composite component:

  1. Generally, a derived class of the layout class is created from the layout class. Maybe in the combo box, We will select the horizontal linearlayout as the parent class. Remember, other layout classes can be nested inside, so hybrid components can be a mixture of any component. Note: Just like activity, you can use an external XML file to declare your components or nest them in the code.
  2. In the constructor of the new hybrid component, first, call the constructor of all parent classes and pass in the corresponding parameters. Then you can set other aspects of your hybrid component, where to create the edittext component, and where to create the popuplist component. Note: You can also introduce some attributes and parameters in the XML file. These attributes and parameters can also be used by your hybrid components.
  3. You can also create a time listener to listen to events triggered by the View class in the new component. For example, to listen to the List Option click event, you must update your edittext value after this time.
  4. You may create some of your own properties with access and modification methods. For example, you can set the initial value of edittext and provide methods to access it.
  5. In the derived class of layout, you do not need to reloadonDraw()AndonMeasure()Method, because layout has a better default processing. However, you can reload it if you think it is necessary.
  6. You may also load someonSeries functions, suchonKeyDown()You can press a key to select the corresponding value in the list.

In short, the layout class as the base class has the following advantages:

  • Like activity, you can declare your new component through an XML file, or you can nest it in code.
  • onDraw()Functions andonMeasure()There is no need to reload functions. The two functions have already done well.
  • You can quickly create your hybrid components and use them as a single component.
Example of a hybrid component (examples of compound controls)

In the API demos project, there are two examples of List classes in the API demos project: Example 4 and Example 6. The speechview component in it is derived from the linearlayout class, the original code isList4.javaAndList6.java.

Adjust existing components (tweaking an existing component)

In some cases, you may have a simpler way to create your components. If you have a very similar component, all you have to do is simply derive your component from this component, focusing on some of the necessary modifications. You can use the same method to completely customize components, but you can simply obtain some existing processing mechanisms by deriving new components from the view, these are probably what you want, and there is no need to start from scratch.

For example, there is a notepad application in the SDK ). This example demonstrates many practical details of the Android platform. For example, you will learn how to derive a notepad that can automatically wrap lines from editview. This is not a perfect example, because these APIs have changed a lot compared to earlier versions, but it does illustrate some problems.

If you haven't checked the program, you can now import the notepad routine in eclipse (or view the source code only through the provided link ). Especially in noteeditor. JavaMyEditText.

Note the following:

  1. Declaration (the definition)

    This class is defined by the following code line:

    public static class MyEditText extends EditText

    • It is defined inNoteEditor activityClass, but it is a common (public), So if necessary, it canNoteEditor.MyEditTextSlaveNoteEditorOutside.
    • It isstaticClass (static class), which means that the so-called "virtual state method" for accessing data through the parent class will not appear, so that the class can become a non-seriously dependentNoteEditor. This is a clear idea for creating inline classes that do not need to be accessed from external classes. It ensures that the generated classes are small and can be conveniently called by other classes.
    • It isEditTextClass extension, which is the parent class we choose to use to customize. After this is done, the new class can be used as a commonEditText.
  2. Class initialization

    Generally, the parent class is called first. Furthermore, this is not a default constructor, but a constructor with parameters. BecauseEditTextIs created using parameters extracted from the XML layout file. Therefore, our constructor also needs to retrieve parameters and pass these parameters to the parent class.

  3. Method overload

    In this example, onlyonDraw()Reload a method. However, you can easily reload other required methods for your custom components.

    For the notepad exampleonDraw()You canEidtViewCanvas (canvas) Draw blue lines (canvasThe class is rewritten.onDraw()Method transfer ). This function will be called when it is about to endsuper.onDraw()Function. The method of the parent class should be called, but in this example, we call it after we have drawn the blue line.

  4. Use custom components

    Now we already have our own custom components, But how should we use them? In the notepad example, the custom components are directly used in the predefined layout file. Let's take a look.res/layoutDirectoryNote_editor.xml file.

    <view xmlns:android="http://schemas.android.com/apk/res/android" 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" />
    • This custom component is created as a general view class in XML and is described through the full path package. Note that the inline class is passed throughNoteEditor$MyEditTextThis is the standard method that references inline classes in Java programming.
    • Other attributes and parameters in the definition will be passed to the constructor of the custom component before being passed to the edittext constructor. Therefore, these parameters are also parameters of the edittext component. Note: You can also add your own parameters here. We will discuss this issue below.

This is all you need to do. It is a simple example. But the key to the problem is: how complicated your requirements are, how complicated your custom components are.

A more complex component may need to overload moreonSeries functions, and many special functions are required to fully implement the functions of custom components. The only limit is your imagination and what work you need components to perform.

Start your componentization journey now

As you can see, Android provides a sophisticated and powerful component model that allows you to do your work as much as possible. From simple component adjustment to component mixing, or even completely custom components, you can use these technologies flexibly to get an android program that fully meets your appearance requirements.

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.