Android Custom View Step _android

Source: Internet
Author: User
Tags garbage collection

Examples are: The Android custom view Password Box example

1 Good Custom view

Easy to use, standard, open.

A well-designed custom view is similar to the other well-designed classes. Encapsulates a functional combination of easy-to-use interfaces that can efficiently use CPU and memory and are very open. However, in addition to starting a well-designed class, a custom view should:

• Compliant with Android standards

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 define the interface of your view carefully to reduce the amount of time you spend in future maintenance. One 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 inherited view full custom or inherited view derived subclasses

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 as a attributeset to the view's constructor.

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

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

All base classes, derived classes, and standard system classes integrated into the Android framework layer, refer directly to these system classes in the SDK and their APIs

2.2 Define custom attributes

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

Add <declare-styleable> resources to the project team. These resources are usually placed in RES/VALUES/ATTRS.XM files. The following is an example of a attrs.xml file:

<resources>;
<declare-styleable name= "Piechart" >
<attr name= "Showtext" format= "boolean"/> <attr "name="
LabelPosition "format=" enum ">
<enum name=" left "value=" "/> <enum name=
" right "value=" "/>
</attr>
</declare-styleable>
</resources>

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

Layout XML files can be used like built-in properties. The only difference is that custom attributes belong to different namespaces.

Http://schemas.android.com/apk/res/[the package path where your custom view is located]

<?xml version= "." Encoding= "utf-"?> <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 Get custom properties

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

L A resource reference with a value is not processed

L style is not allowed

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

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

Public Piechart (Context ctx, AttributeSet attrs) {
super (CTX, attrs);
TypedArray a = Context.gettheme (). Obtainstyledattributes (
attrs,
R.styleable.piechart,
,);
try {
mshowtext = A.getboolean (R.styleable.piechart_showtext, false);
Mtextpos = A.getinteger (r.styleable.piechart_labelposition,);
} finally {
a.recycle ();
}
}

Note that the Typedarry object is a shared resource, and you must recycle it when you are finished using it.

2.4 Add properties and Events

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

public Boolean Isshowtext () {return
mshowtext;
}
public void Setshowtext (Boolean showtext) {
mshowtext = Showtext;
Invalidate ();
Requestlayout ();
}

Note that the Setshowtext calls invalidate () and Requestlayout (). The key to these calls is to ensure that the view behavior is reliable. You must remove this view after changing the attributes that may change the appearance so that the system knows that it needs to be redrawn. Similarly, if a property change can affect the size or view shape, you need to request a new layout. Forgetting to call these methods can cause bugs that are hard to find.

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 rewrite the OnDraw () method. The OnDraw () argument is that the view can be used to draw its own canvas object. The canvas definition is used to draw text, lines, bitmaps, and other image cells. 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 a line, and paint provides a way to define the line color. Canvas provides a way to draw a rectangle, while paint defines whether to fill the rectangle with color or to 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 paint with a separate thread.

3 optimization

3.1 Reduce refresh frequency

In order to improve the running speed of the view, the unnecessary code from the frequently invoked program is reduced. Start the call from the OnDraw () method, which will bring you the best return. In particular, you should reduce redundant code in the OnDraw () method, and redundant code will bring a garbage collection that makes your view incoherent. The initialization of redundant objects, or between animations, will never contribute when the animation is running.

Plus to make the OnDraw () method more dependent, you should try not to call it as frequently as possible. Most of the time the call to the OnDraw () method is the result of calling invalidate (), so the unnecessary call to the invalidate () method is reduced. It is possible to invoke the different types of invalidate () of the four parameters instead of calling the parameterless version. No parametric need to refresh the entire view, and the variables of the four parameter types only need to refresh the view in the specified section. This efficient invocation is closer to requirements and reduces unnecessary refreshing of pages that fall outside the rectangular screen.

3.2 Using hardware acceleration

As the ANDROID3.0,ANDROID2D chart system can be increased by using most of the new Android devices with a GPU (a chart-processing unit), GPU hardware acceleration can be a huge performance boost for many applications, but for each application, is not always the right choice. The Android framework layer better gives you the ability to control whether part of your application's hardware increases.

How to use the acceleration class in your application, activity, or form level, check out the hardware acceleration class in the Android Developer's Guide. Note the additional instructions in the Developer's Guide that you have to <USES-SDK android:targetsdkversion= "one" in your Androidmanifest.xml file/> The application target APIs are set to 11 or higher.

Once you use the hardware acceleration class, you may not see the performance growth, the cell phone GPUs is very good at certain tasks, such as measuring, flipping, and peacefully shifting picture class pictures. In particular, they are not good at other tasks, such as drawing lines and curves. To take advantage of the GPU acceleration class, you should increase the number of operations 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.