Original address: http://android.xsoftlab.net/training/custom-views/index.html
Introduction
The Android framework contains a large number of view classes, which are used to display a wide range of data and interact directly with the user. But at some point, the app has a very special need, but the view in the frame does not meet the need, then you need to create a new view class on your own. This lesson will learn how to create such a custom view.
Create a View class
A well-designed custom view is similar to any other well-designed view class. It encapsulates a range of special features and exposes an easy-to-use interface. It uses the CPU and memory resources efficiently and reasonably. In addition to implementing these features, custom view also requires:
- Follow the Android standard.
- Provides custom style properties that can work in an Android XML layout.
- Sends an accessible event.
- Android platform compatibility.
The Android Framework provides a series of base classes and XML tags to help you create a view that meets the above criteria. This lesson will learn how to use the Android framework to create the core features of a custom view.
Create a subclass of a view
All view classes in Android inherit from view. Custom view can inherit the view directly or inherit view subclasses such as button.
In order for Android Developer tools to interact with your view, you should provide at least one construction method that contains the context and AttributeSet as parameters. This construction method enables the layout editor to create or edit instances of the view.
class PieChart extends View { publicPieChart(Context context, AttributeSet attrs) { super(context, attrs); }}
Defining Custom Properties
If you want to add a view to the UI, you need to specify the view as an XML element and control the behavior and appearance of the view through the element properties. Well-defined custom view also allows you to add and design these styles through XML. In order for the custom view to have these behaviors, you must:
- Define the properties of the custom view in the < declare-styleable > resource element.
- Specifies the value of the property in the XML layout.
- Receives the property value at run time.
- Applies the Received attribute value to the view.
This section will learn how to define properties and how to specify their values. The next section learns how to handle receiving and using these values at run time.
To define custom attributes, you need to add < declare-styleable > resources to your project. These resources are typically placed in the Res/values/attrs.xml file. 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="0"/> <enum name="right" value="1"/> </attr> </declare-styleable></resources>
The above code declares two custom properties, Showtext and LabelPosition, which belong to a style entity named Piechart. The name of a style entity is consistent with the class name of the corresponding custom view according to convention. While it is not necessary to follow this practice, many popular code editors prefer to provide implementation declarations in accordance with this naming convention.
Once custom attributes are defined, you can use them in XML files just like built-in properties. The only difference is that the custom attribute belongs to a different namespace. They are not part of the standard http://schemas.android.com/apk/res/android namespace and belong to the Http://schemas.android.com/apk/res/[your package name]. For example, here's an example of how to use a custom property:
<?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 = custom:labelposition = "left" /> </linearlayout ;
To avoid repeating the definition of namespaces, the XMLS directive is used in the example. This designation causes the Http://schemas.android.com/apk/res/com.example.customviews namespace to be associated with the custom alias. You can use any name you want to use for the namespace.
Note that the custom view referenced here in the layout is named for the permission of the custom view. If the view class is an inner class, it must also be further qualified by the class name of the outer class. For example, Piechart contains an inner class called Pieview. If you want to use a custom property for this class, you should use the label: Com.example.customviews.charting.piechart$pieview.
Apply Custom Properties
When a view is created from an XML layout, all attributes in the XML tag are read and passed to the view in AttributeSet form by the view's construction method. Although it is possible to read data directly from AttributeSet, it has some drawbacks:
- The property value referenced by the resource cannot be parsed
- Style not supported
Conversely, the attributeset can be passed to the Obtainstyledattributes () method. The method returns an Typedarray object that contains an array value that is indirectly referenced.
The android Resource compiler has done a lot of work to make it easier to use the Obtainstyledattributes () method. Each resource in the resource directory will define the corresponding property ID in R.java. You can use this predefined constant to go to the Typedarray to read the property. The following is an example of how the Piechart class reads a property:
publicPieChart(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.PieChart, 00); try { false); 0); finally { a.recycle(); }}
Note Typedarray is a shared resource and must be recycled after it has been used.
Adding Properties and Events
Attributes is a powerful way to control the appearance and behavior of a view, but it is only read when the view is initialized. If you want to provide dynamic behavior, you need to expose the appropriate Get,set method. The following code shows how Piechart exposes an attribute method named Showtext:
publicbooleanisShowText() { return mShowText;}publicvoidsetShowText(boolean showText) { mShowText = showText; invalidate(); requestLayout();}
Note the invalidate () method and the Requestlayout () method are called in Setshowtext. These methods ensure that the behavior changes to the view take effect. You have to redraw the view after you change the completion property to make the view look effective. This way the system will know that the view needs to be redrawn. Similarly, if the new property value may cause changes in size or shape, you will also need to request a new layout. forgetting to call these methods can cause hard-to-find bugs.
Custom view should also support event listeners to interact with important events. For example, Piechart exposes a custom event named Oncurrentitemchanged that notifies the listener user to rotate the pie chart.
It's easy to forget to expose properties and events, especially if you're the only user who has a custom view. When defining the view interface, it takes a little more time and effort to maintain it in the future. A good habit is to always expose the appearance of any member property and the behavior of the property method.
Accessibility
Custom view should support a broader audience. This includes disabled persons with impaired eyesight. In order to support the use of this part of the user, you should:
- Use the Android:contentdescription property to identify your input fields
- Send an accessible event via the Sendaccessibilityevent () method at the appropriate time
- Support for more controllers, such as D-pad and trackball
For more information, see Making applications Accessible.
Android Official Development Document Training Series Course Chinese: Creating a Custom View view