Android Development--building custom components

Source: Internet
Author: User

In Android, your application program has a fixed connection to the view class component, such as a button, text box (TextView), Editable text box (EditText), list box (ListView), check box (checkbox), Radio Box (RadioButton), ScrollBar (Gallery), spinner (Spinner), etc., there are some more advanced view components with special purpose, such as Autocompletetextview, Imageswitcher and Textswitcher. In addition, a wide variety of linear layouts (linearlayout), frame layouts (framelayout), such as layout components (layouts), are also considered as view components, which derive from the view class.

Your application is that these control components and layout components are displayed on the screen in a way that is generally sufficient for you, but you should also know that you can create your own components through class inheritance, and you can generally inherit components like view, Layouts (layout component), Can even be some of the more advanced control class components. Now let's talk about why we should inherit:

    • You can create a completely custom style component for implementing a function, such as creating a control component with two-dimensional graphics to control the sound, just like an electronic control.
    • You can combine several components to form a new component, your component may contain a ComboBox (a list of text that can be entered) and Dual-pane selector control (two list windows, you can assign the dependencies of each of the Windows), and so on.
    • You can create your own layout components (layouts). The layout components in the SDK already provide a range of options for you to build your own applications, but advanced developers will find it necessary to develop new layout components based on existing layout components, or even to develop new components entirely from the ground up.
    • You can override the display or functionality of an existing component. For example, change the way the EditText (editable text) component is displayed on the screen (refer to the Notepad example, which teaches you how to create an underlined display page).
    • You can capture events such as pressing keystrokes, and handle these events in some common way (an example of a game).

In order to achieve some kind of goal you may need to expand an existing view component, let's combine some examples to show you how to do it.

Content:
Basic method (The approach)
Fully customizable component (Fully customized components)
Examples of custom components (customized Component Example)
Component blending (or blending of control classes) (Compound components (or Compound controls))
Modifying existing components (tweaking an Existing Component)
Summary (Go Forth and Componentize)
Basic method (The approach)

Here are a few steps to summarize and teach you how to create your own components:

    1. Let your class inherit an existing view class or a subclass of view.
    2. Some methods of overloading the parent class: The parent class method that requires overloading typically on begins with ' ', such as OnDraw (), Onmeasure (), and OnKeyDown (), and so on.
      • This is also true in the activity or listactivity derivation, where you need to reload some life cycle 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 written by yourself.

Inheriting classes can be defined in activities so that you can easily invoke them, but this is not necessary (perhaps in your application you want to create a component that everyone can use).

Fully customizable component (Fully customized components)

The method of fully customizing the component can create some graphical components for display (graphical component), perhaps a graphic meter like a voltmeter, or a small ball that displays lyrics inside a karaoke bar as the music scrolls. Either way, you can't simply use the combination of components, no matter how you combine these existing components.

Fortunately, you can easily create your own components with your own requirements, and you'll find that it's just your imagination, the size of your screen, and the performance of your processor (remember that your app will only run on platforms that perform less than your desktop).

Here's a quick introduction to creating fully customizable components:

    1. The most common view class's parent class is undoubtedly the view class, so at first you'll create a subclass based on this class.
    2. You can write a constructor to extract attributes and parameters from an XML file, and you can define these attributes and parameters yourself (perhaps the color and size of the graph meter, or the width and amplitude of the pointer, etc.)
    3. You may have to write your own event listeners, access the properties and modify the functions of the function and some of the components themselves on the code.
    4. If you want the component to display something, you are likely to reload onMeasure() the function, so you have to overload the onDraw() function. When two functions are used by default, then the onDraw()  function will not do anything, and the default onMeasure() function automatically sets a 100x100-size, which may not be the size you want.
    5. Other series functions that have the necessary overloads on... need to be re-written once.
onDraw()And onMeasure()

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

Note: Three-dimensional graphics are not included here if you want to use three-dimensional graphics, you should change your parent class from view to Surfaceview class and use a separate thread. You can refer to the example of glsurfaceviewactivity.

onMeasure()The function is a bit tricky because this function is a key part of the interaction between the component and the container, andonmeasure () should be overloaded so that it can effectively and accurately represent the measured values of the part it contains. This is a bit more complicated, because we not only have to consider the limitations of the parent class (passed through onmeasure () ), and we should know that once the width and height are measured, the setmeasureddimension () will be called immediately. Method.

In summary, the execution onMeasure() function is divided into several stages:

    1. Overloaded onMeasure() methods are called, and the height and width parameters are also involved ( widthMeasureSpec and heighMeasureSpec two parameters are integer types), and you should consider the size limits of your product. Here you can refer to view.onmeasure (int, int) (The connection content explains the entire measurement operation in detail).
    2. Your component will onMeasure() display your component by calculating the necessary measurement length and width, which should be consistent with the specification, although it can implement features other than specifications (in this case, the parent can choose what to do, including clipping, sliding, Commit the exception or call the function again with different parameters onMeasure() ).
    3. Once the height and width are calculated, it must be called setMeasuredDimension(int width, int height) , otherwise it will cause an exception.
Example of a custom component (a customized Component Example)

The CustomView in API Demos provides an example of a custom component that is defined in the LabelView class.

The Labelview example involves all aspects of a custom component:

    • First let the custom component derive from the view class.
    • Write a constructor with parameters (parameters can originate from an XML file). Some of this processing has already been done in the view parent class, but some of the new parameters specific to the custom component used by Labelview need to be handled.
    • Some of the standard public functions, for example, setText() setTextSize()setTextColor()
    • Overloaded onMeasure() methods to determine the dimensions of a component (note: In Labelview, it is implemented by a private function measureWidth() )
    • The overloaded onDraw() function displays the lable on the provided canvas.

In the example, you can see the use of custom component Labelview through Custom_view_1.xml. In the XML file, it is particularly important to note the android: app: mixed use of two parameters, which app: represent individuals in the application that are considered to be labelview components, which are also defined as resources in the R class.

Component Blending Technology Compound components (or Compound Controls)

If you do not want to create a fully customized component, but a new component produced by a combination of several existing components, then the hybrid component technology is more appropriate. To put it simply, a couple of existing components can be packaged into a new component in a logical combination. For example, a combo box component can be thought of as a mixture of a 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 other two view classes that can do similar effects: Spinner and Autocompletetextview, but combo box is easier to understand as an example.

Here's a quick introduction to how to create a composite component:

    1. Typically starting with the layout class, create a derived class of the layout class. Perhaps in combo box we will choose the horizontal linearlayout as the parent class. Remember that other layout classes can be nested inside, so a hybrid component can be a mixture of any component. Note that, as with activity, you can either declare your component with an external XML file or nest it in your code.
    2. In the constructor of the new hybrid component, first call all the constructors of the parent class and pass in the corresponding arguments. You can then set up some 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 of your own attributes and parameters into the XML file, which can also be used by your hybrid components.
    3. You can also create a time listener to listen for events triggered by the view class in the new component, for example, to listen for a list option Click event, you must update your EditText value after this time has occurred.
    4. You may create some properties of your own, with access and modification methods. For example, allow the EditText initial value to be set and provide a way to access it.
    5. In the derived class of layout, you do not need to overload onDraw() and onMeasure() method, because layout will have a better default handling. However, if you feel the need you can also reload it.
    6. You can also overload some on series of functions, such as through onKeyDown() overloading, by pressing a key to select the corresponding value in the list.

In summary, there are several advantages to the layout class as a base class:

    • As with activity, you can also declare your new component through an XML file, or you can nest it in your code.
    • onDraw()onMeasure()There is no need for functions and functions to be overloaded, and two functions are well done.
    • You can quickly create your hybrid components, and you can use them as a single component.
Examples of mixed components (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, where the Speechview component is derived from the LinearLayout class to enable display of presentation display functions, The corresponding original code is the List4.java and List6.java .

Adjusting existing components (tweaking an Existing Component)

In some cases, you may have an easier way to create your component. If you should have a very similar component, all you have to do is simply derive your component from this component and weigh in on some of the methods that need to be modified. By fully customizing the component's approach you can do the same, but by generating new components with a flush view derivation, you can simply get some of the existing processing mechanisms that are probably what you want, and there is no need to start from scratch.

For example, there is an example of NotePad in the SDK (NotePad application). This example demonstrates the practical details of many Android platforms, such as the one you'll learn to derive from EditView to automatically wrap a notepad. This is not a perfect example, because these APIs have changed a lot compared to earlier versions, but it does illustrate some of the problems.

If you haven't seen the program yet, you can now import the Notepad routine in eclipse (or simply view the source code by providing a link). In particular, view the MyEditText definitions in Noteeditor.java.

Here are a few things to keep in mind:

  1. Statement (the Definition)

    This class is defined by the following line of code:

    public static class MyEditText extends EditText

    • It is defined in NoteEditor activity the class, but it is common (public), so it can be invoked from the outside if necessary NoteEditor.MyEditText NoteEditor .
    • It is a static class (static Class), meaning that there is no "virtual-state method" that accesses data through the parent class, which makes the class A separate class that can not be heavily relied upon NoteEditor . For the creation of inline classes that do not need to be accessed from an external class, this is a clear way of thinking, guaranteeing that the resulting class is small and allows it to be easily invoked by other classes.
    • It is the extension of the EditText class, and it is the parent class that we choose to use from the definition. When we are done, the new class can be used as an ordinary one EditText .
  2. Initialization of the class

    In general, the parent class is called first. Further, this is not a default constructor, but rather a constructor with parameters. Because EditText it is created using parameters extracted from an XML layout file, our constructors also take out parameters and pass them to the parent class.

  3. method overload

    In this example, only one method of OnDraw () is overloaded. But you can easily reload other required methods for your custom components.

    For the Notepad example, by overloading the OnDraw () method we can draw blue lines on the eidtview canvas ( canvas ) ( The canvas class is passed by the overridden OnDraw () method. The super.ondraw () function is called when the function is nearing completion. The method of the parent class should be called, but in this case we are calling after we have drawn the blue line.

  4. Using custom components

    Now, we already have our own custom components, but how do we use them? In the Notepad example, a custom component is used directly in a predefined layout file, so let's take a look at res/layout thenote_editor.xml文件。



    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"
    • The custom component is created in XML as a generic view class and is described by a full path package. Note that inline classes are represented here NoteEditor$MyEditText , which is the standard way to reference inline classes in Java programming.
    • Other properties and parameters in the definition are passed to the constructor of the custom component before being propagated to the EditText constructor, so these parameters are also parameters that you use with the EditText component. Note that you can also add your own parameters here, and we'll discuss the issue below.

That's all you need to do, admittedly this is a simple example. But the point is: how complex your requirements are, and how complex your custom components are.

A more complex component might need to overload more on series functions, and also require many unique functions to fully implement the functionality of the custom component. The only limitation is your imagination and what you need to do with the component.

Let's start your modular journey now.

As you can see, Android provides a sophisticated and powerful component model that allows you to do your job as much as possible. From simple component sizing to component blending and even full customization of components, using these techniques flexibly, you should be able to get an Android program that perfectly matches your look requirements.

Android Development--building custom components

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.