[Original] Android custom View step

Source: Internet
Author: User

 

Example: Android custom View password

 

1. Good custom View

Easy to use, standard, and open.

A well-designed custom view is similar to other well-designed classes. Encapsulates a combination of functions with easy-to-use interfaces, which can effectively use CPU and memory and are very open. However, apart from starting a well-designed class, a custom view should:

L meets Android standards

L provides custom style attributes that can work in the Android XML Layout

L send accessible events

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 attributes and events, especially when you are the only user of the custom view. Please take some time to carefully define your view interface to reduce the time required for future maintenance. One rule that should be followed is to expose all attributes or behaviors in your view that affect the visible appearance.

2. Create a custom View (STEP) 2.1. inherit the full custom View or inherit the derived subclass of the View

You must provide a constructor that can obtain the Context and attributes of the AttributeSet object to obtain the attributes. After the view is created from the XML layout, all attributes in the XML tag are read from the resource package and passed to the view constructor as an AttributeSet.

Directly or indirectly subclasses derived from View: ImageView, Button, CheckBox, SurfaceView, TextView, ViewGroup, and AbsListView

Directly or indirectly subclasses derived from ViewGourp: AbsoluteLayout, FrameLayout, RelativeLayout, LinearLayout

All base classes and derived classes are standard system classes integrated at the Android framework layer. You can directly reference these system classes and their APIs in the SDK.

2.2 define Custom Attributes

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

Add <declare-styleable> resources to the project team. These resources are usually stored in the res/values/attrs. xm file. The following 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 attribute in your XML layout.

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

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 get the attribute value at runtime.

L apply the retrieved property value to your view.

2.3 get Custom Attributes

After a view is created from the XML layout, all attributes in the XML tag are read from the resource package and passed to the view constructor as an AttributeSet. Although it is possible to directly read values from AttributeSet, it has some disadvantages:

L Resource references with values are not processed

L The style is not allowed

Instead, pass AttributeSet to the obtainStyledAttributes () method. This method returns an array of TypedArray containing the unreferenced and styled values.

In order to make it easier to call the obtainStyledAttributes () method, the Android resource compiler has done a lot of work. For 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 pointing to an array. You can use a predefined constant to read attributes from TypedArry. The following example shows how the PieChart class reads these attributes:

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 recycled after use.

2.4 Add attributes and events

Attribute is a powerful way to control the behavior and appearance of a view, but these attributes are readable only 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 attribute.

1

2

3

4

5

6

7

8

9

Public boolean isShowText (){

ReturnMShowText;

}

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 must abolish this view after changing the attribute that may change the appearance so that the system knows that the view needs to be re-painted. Similarly, if a property change may affect the size or view shape, you need to request a new layout. If you forget to call these methods, it may be difficult to find bugs.

Custom views also support event listeners that communicate with important events.

2.5 custom plotting (Implementation)

The most important step in creating a custom view is to override the onDraw () method. the onDraw () parameter indicates that a view can be used to draw its own Canvas object. a Canvas definition is used to draw text, lines, bitmaps, and other image units. you can use these methods in onDraw () to create your Custom User Interface (UI ).

The android. graphics framework divides a drawing into two parts:

L what to draw, processed by Canvas

L how to Paint, processed by Paint

For example, Canvas provides a method to draw a line, while painting provides a method to define the line color. canvas provides a way to draw a rectangle, while painting defines whether to fill the rectangle with color or leave it empty. in short, Canvas defines the shape you can draw on the screen, while painting defines the color, style, font and so on for each shape you draw.

OnDraw () does not support 3d graphics APIs. To support 3d graphics, you must inherit SurfaceView instead of View and draw images through separate threads.

3. Optimize 3.1 to reduce the refresh frequency

To improve the running speed of view and reduce unnecessary code from frequently called programs. Call 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 lead to garbage collection that makes your view incoherent. Initialization of redundant objects, or between animations, will never contribute when the animation is running.

In addition, to make the onDraw () method more dependent, do not call it as frequently as possible. Most of the time, calling the onDraw () method is the result of calling invalidate (), so it is unnecessary to call the invalidate () method. It is possible to call invalidate () of different types of four parameters, instead of the version without parameters. The entire view needs to be refreshed if there are no parameters. For four parameter types, only the specified view needs to be refreshed. this kind of efficient call is closer to the requirement, and it can also reduce the page that falls outside the rectangular screen and does not need to be refreshed.

3.2 use hardware acceleration

As Android3.0, The Android2D chart system can be increased with a GPU (Chart Processing Unit) provided by most new Android devices. For many applications, the GPU hardware acceleration can bring huge performance increases, however, it is not the right choice for every application. The Android framework layer provides you with the ability to control whether some hardware of an application is added.

For more information about how to use the Acceleration class in your applications, activities, or forms, see the Hardware Acceleration class in the Android developer guide. Note that the additional instructions in the developer guide must be in your AndroidManifest. in the xml file <uses-sdk android: targetSdkVersion = "11"/>, set the application target API to 11 or higher.

Once you use the hardware acceleration class, you may not see performance growth. The mobile GPUs is very good at certain tasks, such as measurement, flip, and peaceful shift graph pictures. In particular, they are not good at other tasks, such as drawing straight lines and curves. To use the GPU acceleration class, you should increase the number of operations that the GPU is good at and reduce the number of operations that the GPU is not good.

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.