Examples are as follows:Android Custom View Password Box Example
1 Good custom view
Easy to use, standard, open.
A well-designed custom view is very similar to other well-designed classes. Encapsulates a combination of functions with ease of use interfaces that can effectively use CPU and memory and are very open. However, in addition to starting a well-designed class, a custom view should:
l Comply with Android standards
l Provides custom style properties that work in Android XML layouts
l Send accessible events
l Compatible with multiple Android platforms.
The Android framework provides a basic set of classes and XML tags to help you create a new view that meets these requirements. It's easy to forget to provide properties and events, especially if you're the only user of this custom view. Please take some time to carefully define the interface of your view to reduce the time spent in 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 (steps)
2.1 Inherit View completely customizes or inherits derivative subclasses of View
It is necessary to provide a constructor that can obtain the Context and AttributeSet object as attributes to obtain the attributes. When 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 as an AttributeSet constructor.
Direct or indirect subclasses derived from View: ImageView, Button, CheckBox, SurfaceView, TextView, ViewGroup, AbsListView
ViewGourp derived direct or indirect subclasses: AbsoluteLayout, FrameLayout, RelativeLayout, LinearLayout
All base classes and derived classes are standard system classes integrated with Android framework layer, which can directly reference these system classes and their APIs in the SDK.
2.2 Define custom properties
l Define custom properties for your view in the resource element <declare-styleable>.
Add a <declare-styleable> resource to the project group. These resources are usually placed in the res/values/ file. Here is an example of a 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 attribute in your XML layout.
You can use them in a layout XML file like built-in properties. The only difference is that custom properties belong to different namespaces.
/apk/res/[The package path where your custom view is located]
<?xml version="." encoding="utf-"?> <LinearLayout xmlns:andro xmlns:custom="/apk/res/"> < custom:showText="true" custom:labelPosition="left" /> </LinearLayout>
l Get the attribute value at runtime.
l Apply the retrieved property value to your view.
2.3Get custom properties
When 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's constructor as an AttributeSet. Although it is OK to read the value directly from the AttributeSet, there are some disadvantages to doing this:
l Resource reference with values is not processed
The style is not allowed
Instead, pass the AttributeSet to the obtainedStyledAttributes() method. This method returns a TypedArray array containing the values that have been dereferenced and styled.
In order to make it easier to call the obtainedStyledAttributes() method, the Android resource compiler has done a lot of work. Each <declare-styleable> resource in the res folder generates an array of attribute IDs and a set of constants that define each attribute in the array. You can read properties from TypedArry using predefined constants. The following example is how the PieChart class reads these properties:
public PieChart(Context ctx, AttributeSet attrs) { super(ctx, attrs); TypedArray a = ().obtainStyledAttributes( attrs, , , ); try { mShowText = (.PieChart_showText, false); mTextPos = (.PieChart_labelPosition, ); } finally { (); } }
Note that the TypedArry object is a shared resource and must be recycled after use.
2.4Add properties and events
Attributes are a powerful way to control the behavior and appearance of a view, but these properties are readable only after the view is initialized. In order to provide dynamic behavior, a pair of getters and setters for each custom attribute need to be exposed. The following code snippet shows how PieChart provides the showText property.
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 must abolish this view after changing this property that may change the appearance, so that the system knows that it needs to be redrawn. Similarly, if the change in the property may affect the size or the shape of the view, you need to request a new layout. Forgot to call these methods can cause difficult-to-find bugs.
Custom view also requires event listeners that support communication with important events.
2.5Custom drawing (implementation)
The most important step in drawing a custom view is to override the onDraw() method. The onDraw() parameter is that the view can be used to draw its own Canvas objects. The 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 frame divides the drawing into two parts:
l What to draw, handled by Canvas
l How to draw, handled by Paint
For example, Canvas provides methods to draw lines, while Paint provides methods to define the color of the line. Canvas provides methods to draw rectangles, while Paint defines whether to fill the rectangle with color or make it empty. In short, Canvas defines the shapes you can draw on the screen, while Paint defines the color, style, font, etc. for each shape you draw.
onDraw() does not provide support for 3D graphics APIs. If you need 3d graphics support, you must inherit the SurfaceView instead of the View and draw it through a separate thread.
3 Optimization
3.1Reduce the refresh frequency
In order to increase the speed of the view, unnecessary code from frequently called programs is reduced. Start calling with the onDraw() method, which will give you the best reward. In particular, in the onDraw() method you should reduce redundant code, which will bring about garbage collection that makes your view incoherent. Initialized redundant objects, or between animations, will never contribute when the animation is running.
In addition, in order to make the onDraw() method more dependent, you should not call it as frequently as possible. Most of the time, calling the onDraw() method is the result of calling invalidate(), so unnecessary calls to invalidate() method are reduced. It is possible to call invalidate() of four parameters with different types, rather than calling the non-argument version. No parameter variables need to refresh the entire view, while variables of the four parameter types only need to refresh the view of the specified part. This efficient call is closer to the requirement and can also reduce unnecessary refresh pages falling outside the rectangular screen.
3.2 Using hardware acceleration
As Android 3.0, the Android 2D charting system can be added by most new Android devices with their own GPU (chart processing unit). For many applications, GPU hardware acceleration can bring huge performance increases, but for every application, it is not the right choice. The Android framework layer better provides you with the ability to control whether some of the hardware of the application is increased.
To use acceleration classes at your application, activity, or form level, please refer to the Hardware Acceleration class in the Android Developer Guide. Note the additional instructions in the developer's guide that you must set the application target API to 11 or higher in <uses-sdk android:targetSdkVersion="11"/> in your file.
Once you use the hardware acceleration class, you may not see performance growth, mobile GPUs are very good at certain tasks such as measuring, flipping, and panning pictures of the bitmap class. In particular, they are not good at other tasks such as drawing straight lines and curves. To take advantage of 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 at.