[Original] Android Custom view step

Source: Internet
Author: User

Examples are:Android custom View Password Box example

1 Good Custom view

Easy to use, standard, open.

A well-designed custom view is similar to other well-designed classes. Encapsulates a feature combination with an easy-to-use interface that can be used efficiently with CPU and memory, and is very open. However, in addition to starting a well-designed class, a custom view should:

L complies with Android standard

L provide custom style properties that work in the Android XML layout

L Send an accessible event

L compatible with multiple Android platforms.

The Android framework provides a set of basic classes and XML tags to help you create a new view that meets these requirements. It is easy to forget to provide properties and events, especially if you are the only user of this custom view. Take some time to carefully define your view's interface to reduce the time spent in future maintenance. A guideline to follow is to expose all properties or behaviors that affect the visible appearance in your view.

2 Create a custom view (step) 2.1 inherit view derived subclasses that fully customize or inherit view

You must provide a constructor that gets the context and the AttributeSet object as a property, gets the property, and when view is created from the XML layout, All attributes in the XML tag are read from the resource bundle and passed to the view's constructor as a attributeset.

View derived direct or indirect subclass: ImageView, Button, CheckBox, Surfaceview, TextView, ViewGroup, Abslistview

Viewgourp derived from direct or indirect subclasses: Absolutelayout, Framelayout, Relativelayout, LinearLayout

All base classes, derived classes are standard system classes that are integrated into the Android framework layer and can directly reference these system classes and their APIs in the SDK

2.2 Defining custom Properties

L Define custom properties for your view in resource element <declare-styleable>.

Add <declare-styleable> resources to a project group. These resources are usually placed in the Res/values/attrs.xm file. Here is an example of the Attrs.xml file:

1

2

3

4

5

6

7

8

9

<resources>;

<declare-styleable name= "Piechart" >

<attr name= "Showtext" format= "boolean"/>

<attr name= "LabelPosition" format= "enum" >

<enum name= "left" value= "0"/>

<enum name= "Right" value= "1"/>

</attr>

</declare-styleable>

</resources>

L Use the value of the specified property in your XML layout.

Layout XML files can be used in the same way as built-in properties. The only difference is that the custom attribute belongs to a different namespace.

Http://schemas.android.com/apk/res/[your Package Name]

1

2

3

4

5

6

7

<?xml version="1.0"encoding="utf-8"?>

<LinearLayout xmlns:android="Http://schemas.android.com/apk/res/android"

xmlns:custom="Http://schemas.android.com/apk/res/com.example.customviews">

<com.example.customviews.charting.PieChart

custom:showText="true"

custom:labelPosition="left"/>

</LinearLayout>

L Gets the property value at run time.

L APPLY the retrieved property values to your view.

2.3 Getting custom properties

When view is created from an XML layout, all attributes in the XML tag are read from the resource bundle and passed to the view's constructor as a attributeset. Although it is possible to read the values directly from the AttributeSet, there are some drawbacks to doing so:

L Resource reference with value not processed

L style does not get allowed

Instead, pass the AttributeSet to the Obtainstyledattributes () method. This method returns a Typedarray array containing the values that have been dereferenced and styled.

To make it easier to call the Obtainstyledattributes () method, the Android Resource compiler does a lot of work. Each <declare-styleable> resource in the Res folder, the generated R.java defines an array of property IDs and a set of constants that define each property in the array. You can use predefined constants to read properties from Typedarry. The following example is how the Piechart class reads these properties:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Public Piechart (Context ctx, AttributeSet attrs) {

Super (CTX, Attrs);

TypedArray a = Context.gettheme (). Obtainstyledattributes (

Attrs,

R.styleable.piechart,

0, 0);

Try {

Mshowtext = A.getboolean (R.styleable.piechart_showtext, false);

Mtextpos = A.getinteger (r.styleable.piechart_labelposition, 0);

} finally {

A.recycle ();

}

}

Note that the Typedarry object is a shared resource and must be reclaimed after it is used.

2.4 Adding Properties and Events

Properties are a powerful way to control the behavior and appearance of a view, but only those properties are readable after the view is initialized. To provide dynamic behavior, you need to expose a pair of getter and setter for each custom attribute. The following code snippet shows how Piechart provides the Showtext property.

1

2

3

4

5

6

7

8

9

public Boolean isshowtext () {

return Mshowtext;

}

public void Setshowtext (Boolean showtext) {

Mshowtext = Showtext;

Invalidate ();

Requestlayout ();

}

Note that Setshowtext calls invalidate () and Requestlayout (). The key to these calls is to ensure that the view behavior is reliable. You have to remove the view after changing the properties that might change the appearance, so the system knows it needs to be redrawn. Similarly, if the property changes may affect the size or the shape of the view, you need to request a new layout. Forgetting to call these methods can lead to difficult-to-find bugs.

Custom view also requires event listeners that support and communicate important events.

2.5 Custom Drawing (Implementation)

The most important step in drawing a custom view is to override the OnDraw () method. The argument to OnDraw () is that the view can be used to draw its own canvas object. Canvas definitions are used to draw text, lines, bitmaps, and other image units. You can use these methods in OnDraw () to create your own custom user interface (UI).

The Android.graphics framework divides the drawing into two parts:

L Draw what, handled by canvas

L How to draw, handled by paint

For example, Canvas provides a way to draw lines, and paint provides a way to define line colors. Canvas provides a way to draw a rectangle, and paint defines whether to fill the rectangle with color or leave it blank. In short, canvas defines the shapes you can draw on the screen, and paint defines colors, styles, fonts, and so on for each shape you draw.

OnDraw () does not provide support for the 3d graphics API. If you need 3d graphics support, you must inherit Surfaceview instead of view and draw from a separate thread.

3 Optimization 3.1 Reduced refresh rate

To improve the speed of view, it reduces unnecessary code from frequently called programs. Start the call from the OnDraw () method, which will give you the best return. In particular, you should reduce redundant code in the OnDraw () method, and redundant code will result in a garbage collection that makes your view incoherent. Initializing redundant objects, or between animations, will never contribute when the animation is running.

In addition, to make the OnDraw () method more dependent, you should not call it as often as possible. Most of the time calling the OnDraw () method is the result of calling invalidate (), so reduce the unnecessary call to the invalidate () method. It is possible to call four parameters of different types of invalidate () instead of calling the version without arguments. No parametric needs to refresh the entire view, while variables of the four parameter types only need to refresh the view of the specified part. This efficient invocation is closer to demand and reduces unnecessary refreshes of pages that fall outside the rectangular screen.

3.2 Using hardware acceleration

As the ANDROID3.0,ANDROID2D chart system can be increased by bringing the GPU (chart processing unit) to most new Android devices, GPU hardware acceleration can have a huge performance gain for many applications, but for each application, Not all of them are the right choice. The Android framework layer provides you with the ability to control whether part of your application's hardware increases.

How to use acceleration classes in your app, activity, or form level, check out the hardware acceleration class in the Android developer guide. Note the additional instructions in the Developer guide that you have to <USES-SDK android:targetsdkversion= "one" in your Androidmanifest.xml file/> Set the app target API to a level of 11 or higher.

Once you use the hardware acceleration class, you may not see the performance growth, the phone GPUs is very good at certain tasks, such as measuring, flipping, and peacefully shifting pictures of the graph class. In particular, they are not good at other tasks, such as drawing straight lines and curves. To take advantage of GPU acceleration classes, you should increase the number of operations that the GPU excels at and reduce the number of operations that the GPU is not good at.

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.