Android Custom View Steps

  • 2021-07-24 11:47:43
  • OfStack

Examples are as follows: Android custom View password box example

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 features with an easy-to-use interface that efficiently uses CPU and memory and is 10-point open. However, in addition to starting a well-designed class, a custom view should:

l meets Android standard

l provides custom style properties that work in an Android XML layout

l sends accessible events

l is 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 is easy to forget to provide properties and events, especially if you are the only user of this custom view. Take a moment to carefully define your view interface to reduce future maintenance time. One guideline to follow is to expose any attributes or behaviors in your view that affect the visual appearance.

2 Create a custom View (step)

2.1 Inheriting View Completely customizing or inheriting derived subclasses of View

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

Direct or indirect subclasses derived from View: ImageView, Button, CheckBox, SurfaceView, TextView, ViewGroup, AbsListView

Direct or indirect subclasses derived from ViewGourp: AbsoluteLayout, FrameLayout, RelativeLayout, LinearLayout

All base classes and derived classes are standard system classes integrated in Android framework layer. These system classes in SDK and API can be directly referenced

2.2 Defining Custom Properties

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

Add in the project group < declare-styleable > Resources. These resources are usually placed in the res/values/attrs. xm file. Here is an example of the 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 uses the values of the specified attributes in your XML layout.

They can be used in the layout XML file like the built-in attribute 1. The only difference is that custom attributes belong to different namespaces.

http://schemas. android. com/apk/res/[Package Path for Your Custom View]


<?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 property values at run time.

l applies the retrieved attribute value to your view.

2.3 Getting Custom Properties

After the view is created from the XML layout, all the attributes in the XML tag are read from the resource bundle and passed as an AttributeSet to the constructor of view. Although it is possible to read values directly from AttributeSet, this has one drawback:

l Resource references with values are not processed

The l style is not allowed

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

The Android resource compiler has done a lot of work to make it easier to call the obtainStyledAttributes () method. Each in the res folder < declare-styleable > Resource, the resulting R. java all define an array of attributes ID and a set of constants that define points to each of the attributes in the array. You can read properties from TypedArry using predefined constants. The following example shows 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, which must be recycled after use.

2.4 Add Properties and Events

Attributes are a powerful way to control the behavior and appearance of an view, but they are readable only after the view is initialized. To provide dynamic behavior, one pair of getter and setter for each custom attribute needs to be exposed. The following code snippet shows how PieChart provides showText attributes.


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 view behavior is reliable. You must abolish the view after changing the property that may change the appearance, so that the system will know that it needs to be redrawn. Likewise, if a property change may affect the size or the shape of the view, you need to request a new layout. Forgetting to call these methods may lead to an bug that is difficult to find.

Custom view also requires event listeners that support communication with 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 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 android. graphics framework divides the drawing into two parts:

What does l draw, processed by Canvas

How to draw l is handled by Paint

For example, Canvas provides a way to draw lines, while Paint provides a way to define line colors. Canvas provides a way to draw rectangles, while Paint defines whether to fill the rectangle with color or leave it empty. In short, Canvas defines the shapes you can draw on the screen, while Paint defines colors, styles, fonts, etc. for each shape you draw.

onDraw () does not provide support for 3d graphics api. If you need 3d graphics support, you must inherit SurfaceView instead of View and draw through a separate thread.

3 Optimization

3.1 Reduce Refresh Frequency

In order to improve the running speed of view and reduce unnecessary code from frequently called programs. Start with the onDraw () method, which will bring you the best return. In particular, you should reduce redundant code in the onDraw () method, which leads to garbage collection that makes your view incoherent. Redundant objects initialized, or between animations, will never contribute while the animation is running.

In addition, to make the onDraw () method more dependent, you should try not to call it as often as possible. Most of the time, calling the onDraw () method is the result of calling invalidate (), thus reducing unnecessary calls to the invalidate () method. It is possible to call four invalidate () with different types of parameters instead of calling the parameterless version. Parameterless variables need to refresh the whole view, while variables of four parameter types only need to refresh the specified part of view. This efficient call is closer to the demand, and can also reduce unnecessary refreshed pages that fall outside the rectangular screen.

3.2 Using Hardware Acceleration

As an Android3.0, the Android2D chart system can be augmented with most of the new Android devices coming with GPU (chart processing unit). For many applications, the GPU hardware acceleration can bring huge performance gains, but for every application, it is not always the right choice. The Android framework layer gives you better control over the addition of hardware to parts of your application.

See the Hardware Acceleration class in the Android Developer's Guide for how to use acceleration classes at your application, activity, or form level. Note the additional instructions in the developer's guide, you must be in your AndroidManifest. xml file < uses-sdk android:targetSdkVersion="11"/ > Set the application target API to 11 or higher.

1 Once you use the hardware acceleration class, you may not see the performance increase. The mobile phone GPUs is very good at certain tasks, such as measuring, flipping, and shifting pictures. 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 GPU is good at and reduce the number of operations that GPU is not good at.


Related articles: