Android how to custom view

Creating custom and compound views in Android — Tutorial

This tutorials describes how to create custom and combound views with Android.

1. Custom Views

1.1. Default views

The Android framework provides several default views. The base class a view is the View . Views are responsible for measuring, layouting and drawing themselves and their child elements (in case of a ViewGroup ). Views are also responsible for saving their UI state and handling touch events. Developers can also create custom views and use them in their application.

It is possible to create custom views by:

Compound views — combining views with a default wiring

Custom views — creating your own views

by extending an existing view, e.g. Button

by extending the View class

The following image shows the default view hierarchy of Android.

View are typically created to provide a user interface experience with is not possible with the default views. Using custom view allows the developer allow to do certain performance optimization, i.e., in case of a custom layout the development can optimize the layout manager for his use case.

1.2. How Android draws the view hierarchy

Once an activity receives the focus, it must provide the root node of its layout hierarchy to the Android system. Afterwards the Android system starts the drawing procedure.

Drawing begins with the root node of the layout. The layout hierarchy is traversed in the order of declaration, i.e., parents are drawn before their children and children are drawn in the order of declaration.

Drawing the layout is a two pass process:

measuring pass — implemented in the`measure(int, int)` method. This happens as a top-down traversal of the view hierarchy. Every view stores its measurements.

layout pass — implemented in the layout(int, int, int, int) method. This is also a top-down traversal of the view hierarchy. During this phase each layout manager is responsible for positioning all of its children. It uses the sizes computed in the measure pass.

The measure and layout step always happen together.

Layout managers can run the measure pass several times. For example, LinearLayout supports the weight attribute which distributes the remaining empty space among views and RelativeLayout measures child views several times to solve constraints given in the layout file.

A view or activity can trigger the measure and layout pass with a call to the requestLayout() method.

After the measure and layout calculation, the views draw themselves. This operation can be triggered with the invalidate() method from the View class.

For a detailed introduction into the deeper layer of Android see http://source.android.com/devices/graphics/architecture.html.

1.3. Using new views in layout files

Custom and compound views can be used in layout files. For this you need to use the full qualified name in the layout file, e.g. using the package and class name.

Alternatively you can also declare you name space in the layout file, similar to the Android name space.

1.4. Create screenshots of views

Every View class support the creating of an image of its current display. The following coding shows an example for that.

2. Compound Views

Compound views (also known as Compound Components ) are pre-configured ViewGroups based on existing views with some predefined view interaction.

Combound views also allow you to add custom API to update and query the state of the combound view.

For such a control you define a layout file and assign it to your compound view. In the implementation of your compound view you predefine the view interaction. You would define a layout file and extend the corresponding ViewGroup class. In this class you inflate the layout file and implement the View connection logic

For performance reasons you may want to rewrite your combound view to a custom view which extends View . This may you can typically flatten your view hierarchy. Drawing the view requires in this case less traversals and this can be significantly faster if implemented correctly.

Читайте также:  Google map спутник для андроида

3. Creating custom views

3.1. Creating custom views

By extending the View class or one of its subclasses you can create your custom view.

For drawing view use the onDraw() method. In this method you receive a Canvas object which allows you to perform drawing operations on it, e.g. draw lines, circle, text or bitmaps. If the view should be re-drawn you call the invalidate() method which triggers a call to the onDraw() method of this view.

If you define own views, ensure you review the ViewConfiguration class, as it contains several constants for defining views.

To draw your Views you typically use the 2D Canvas API.

3.2. Measurement

The layout manager calls the onMeasure() method of the view. The view receives the layout parameter from the layout manager. A layout manager is responsible to determine the size of all its children.

The view must call the setMeasuredDimenstion(int, int) method with the result.

3.3. Defining custom layout managers

You can implement your custom layout manager by extending the ViewGroup class. This allows you to implement more efficient layout managers or to implement effects which are currently missing in the Android platform.

A custom layout manager can override the onMeasure() and onLayout() method and specialize the calculation of its children. For example it can leave out the time consuming support of layout_weight of the LinearLayout class.

To calculate the size of the child you can use the measureChildWithMargins() method of the ViewGroup class.

It is good practice to store any additional layout parameters in an inner class of your ViewGroup implementation. For example ViewGroup.LayoutParams ` implements command layout parameters, and `LinearLayout.LayoutParams implements additional parameters specific to LinearLayout, as for example the layout_weight parameter.

4. Life cycle of a Andoid view

A view is displayed if it is attached to a layout hierarchy which is attached to a window. A view has several life cycle hooks.

The onAttachedToWindow() is called once the window is available.

The onDetachedFromWindow() is used when the view is removed from its parent (and if the parent is attached to a window). This happens for example if the activity is recycled (e.g. via the finished() method call) or if the view is recycled.

The onDetachedFromWindow() method can be used to stop animations and to clean up resources used by the view.

4.2. Traversal life cycle events

Traversals life cycle events consists of Animate, Measure, Layout and Draw.

All views must know how to measure and layout themselves. The requestLayout() method call tells the view to measure and layout itself. As this operation may influence the layout of other views it calls also requestLayout() of its parent.

This recursive call is the reason why you should not nestle layout to deeply. The measure and layout operation might be expensive if a lot of hierarchies are re-calculated.

The onMeasure() method determines the size for the view and its children. It must set the dimension via the setMeasuredDimension() method in this method call before returning.

The onLayout() positions the views based on the result of the onMeasure() method call. This call happens typically once, while onMeasure() can happen more than once.

4.3. Activity life cycle

Views don’t have access to the life cycle events of the activities. If views want to get informed about these events, you should create an interface in the view which you call in the life cycle methods of the activity.

5. Define additional attributes for your custom Views

You can define additional attributes for your compound or custom views. To define additional attributes create an attrs.xml file in your res/values folder. The following shows an example of attributes defined for a new view called ColorOptionsView .

To use these attributes in your layout file you have to declare them in the XML header. In the following listing this is done via the xmlns:custom part of the code. These attributes are also assigned to the view.

The following example shows how you components can access these attributes.

Источник

Android SDK: Creating Custom Views

The Android platform provides an extensive range of user interface items that are sufficient for the needs of most apps. However, there may be occasions on which you feel the need to implement a custom user interface for a project you are working on. In this tutorial we will work through the process of creating a custom View.

Читайте также:  Android studio подключение github

To create and use our custom View, we will extend the View class, define and specify some custom attributes, add the View to our layout XML, override the onDraw method to tailor the View appearance and manipulate it from our app’s main Activity.

Step 1: Create an Android Project

Create a new Android project in Eclipse. You can choose whatever settings you like as long as your app has a main Activity class and a layout file for it. We do not need any amendments to the Manifest file. In the source code download file the main Activity is named «LovelyActivity» and the layout file is «activity_lovely.xml» — alter the code to suit your own names if necessary. We will be creating and adding to a few additional files as we go along.

Step 2: Create a View Class

Our custom View can extend any of the existing Android View classes such as Button or TextView. However, we will create a direct subclass of View. Extending an existing class allows you to use the existing functionality and styling associated with that class, while providing processing to suit your own additional needs.

Create a new class in your application by selecting the app’s main package in Eclipse and choosing «File», «New», «Class». Enter a name of your choice and click «Finish». The tutorial code uses the class name «LovelyView» — you will need to alter it in all of the below code if you choose a different name. Make your new class extend View by adding to its opening declaration line:

Add the following import statements above this:

Step 3: Create Attribute Resources

In order to use our custom View as we would use a standard View (i.e. set its attributes in layout XML and refer to them in our Java code), we will declare attribute resources. In Eclipse, create a new file in your project «res/values» folder by selecting it and choosing «File», «New», «File». Enter «attrs.xml» as the file name and click «Finish».

In the attributes file we first need to indicate that we are listing resources, so add the following parent element:

Inside this element, we are going to declare three attributes for the View that will allow us to style it. Let’s keep things relatively simple — the View is going to display a circle with some text in the middle. The three attributes will be the circle color, the text String, and the text color. Add the following inside your resources element:

The declare-styleable element specifies the View name. Each attribute has a name and format. We will be able to specify these attributes in the layout XML when we add the custom View and also retrieve them in the View class. We will also be able to retrieve and set the attributes from our Java Activity class. The values provided for each attribute will need to be of the type listed here as format.

Step 4: Add the View to the Layout

Let’s add an instance of the custom View to our app’s main layout file. In order to specify the custom View and its attributes, we need to add an attribute to the parent layout element. In the source download, it is a RelativeLayout but you can use whichever type you prefer. Add the following attribute to your layout’s parent element:

Alter «your.package.name» to reflect the package your app is in. This specifies the namespace for our app, allowing us to use the attributes we defined within it. Now we can add an instance of the new View. Inside the layout, add it as follows:

Again, alter the package name to suit your own, and the class name if necessary. We will use the ID to refer to the View in our Activity code. Notice that the element lists standard View attributes alongside custom attributes. The custom attributes are preceded by «custom:» and use the names we specified in our attributes XML file. Note also that we have specified values of the types we indicated using the format attributes in the «attrs.xml» file. We will retrieve and interpret these values in our View class.

Step 5: Retrieve the Attributes

Now let’s turn back to the View class we created. Inside the class declaration, add some instance variables as follows:

We will use the first three of these to keep track of the current settings for color and text. The Paint object is for when we draw the View. After these variables, add a constructor method for your class:

Читайте также:  Свап файл для андроид

As we are extending the View class, the first thing we do is call the superclass method. After the super call, let’s extend the method to setup the View. First instantiate the Paint object:

Now let’s retrieve the attribute values we set in XML:

This typed array will provide access to the attribute values. Notice that we use the resource name we specified in the «attrs.xml» file. Let’s now attempt to retrieve the attribute values, using a try block in case anything goes wrong:

We read the attributes into our instance variables. Notice that we use the names we listed for each in «attrs.xml» again. The colors are retrieved as integer values and the text label as a String.

That’s the constructor method complete — by the time it has executed, the class should have retrieved the selected View attributes we defined in the attribute resources file and set values for in the layout XML.

Step 6: Draw the View

Now we have our View attributes in the class, so we can go ahead and draw it. To do this, we need to override the onDraw method. Add its outline after your constructor method as follows:

Since we’re going to draw a circle, let’s get some information about the available space, inside the onDraw method:

Now we can calculate the circle radius:

Now let’s set some properties for painting with:

Now we will use the selected circle color as stored in our instance variable:

This means that the circle will be drawn with whatever color we listed in the layout XML. Let’s draw it now using these details:

Now let’s add the text. First set the color using the value retrieved from the layout XML:

Now set some more properties:

Finally we can draw the text, using the text string retrieved:

That’s onDraw complete.

Step 7: Provide Get and Set Methods

When you create a custom View with your own attributes, it is recommended that you also provide get and set methods for them in your View class. After the onDraw method, first add the get methods for the three customizable attributes:

Each method simply returns the value requested. Now add the set methods for the color attributes:

These methods accept int parameters representing the color to set. In both cases we update the instance variable in question, then prompt the View to be redrawn. This will make the onDraw method execute again, so that the new values affect the View displayed to the user. Now add the set method for the text:

This is the same as the other two set methods except for the String parameter. We will call on these methods in our Activity class next.

Step 8: Manipulate the View from the Activity

Now we have the basics of our custom View in place, let’s demonstrate using the methods within our Activity class. In the app’s main Activity class, add the following import statements:

Before the onCreate method, inside the class declaration, add an instance variable representing the instance of the custom View displayed:

Inside the onCreate method, after the existing code, retrieve this using its ID as included in the XML layout file:

To demonstrate setting the View attribute values from the Activity, we will add a simple button. Open your layout file and add it after the custom View element:

We specify a method to execute on user clicks — we will add this to the Activity class. First add the String to your «res/values/strings» XML file:

Now go back to the Activity class and add the method listed for clicks on the button:

Let’s use the set methods we defined to update the custom View appearance:

This is of course just to demonstrate how you can interact with a custom View within your Activity code. When the user clicks the button, the appearance of the custom View will change.

Conclusion

In general, it’s advisable to use existing Android View classes where possible. However, if you do feel that you need a level of customization beyond the default settings, creating your own custom Views is typically straightforward. What we have covered in this tutorial is really just the beginning when it comes to creating tailored Android user interfaces. See the official guide for information on adding interactivity and optimization to your customizations.

Источник

Оцените статью