[Android trainning translation] create a custom View class

Source: Internet
Author: User

Original address http://developer.android.com/training/custom-views/create-view.html

As mentioned above:For the first translation, the self-knowledge translation is not very good. Therefore, please do not blame the readers (if any). I believe they will do better in the future.

I think there are several reasons for translation:

  1. Exercise my ability to read English
  2. Through careful translation, I can have a deeper understanding of the translation content and learn the knowledge well.
  3. Translating English into Chinese can help other people who have difficulty reading English to learn the knowledge in this article (of course, I have limited ability now, and the translation is very simple, but I hope to translate some good articles in the future)
Create a View class and a well-designed custom view, just like any other well-designed class. It encapsulates a set of specific functions and has an easy-to-use interface that can effectively use CPU and memory. However, in addition to a well-designed class, a custom view should also
  • Meets Android standards
  • Provides custom attributes that can be used in the android XML layout.
  • Send accessible events (this translation is not very good, so it is difficult to understand ...)
  • Compatible with multiple Android platforms
The android framework provides a set of base classes and XML tags to help you create a custom view that meets all these requirements. This topic describes how to use the android framework to create a custom view. Inheriting all view classes defined in a viewandroid framework inherits view classes. Your custom view can also inherit the View class directly, or you can save time by inheriting an existing view subclass, such as the button class. To allow Android developer tools to work with your view, you must provide at least one constructor that contains one context object and one attributeset object as parameters. This constructor allows the layout editor to create and edit an instance of your view.
class PieChart extends View {    public PieChart(Context context, AttributeSet attrs) {        super(context, attrs);    }}

To add a built-in view to your user interface, you must specify an XML element and an element attribute that controls its appearance and behavior. You can also use XML to add and set styles for well-written custom views. To make your custom view have this effect, you must:

  • Define custom attributes for your view in a <declare-styleable> resource element
  • Define attribute values in XML Layout
  • Get attribute values during running
  • Use the obtained property value
This section describes how to define attributes and specify attribute values for them. The next section describes how to obtain and apply these attribute values at runtime. To define custom properties, add <declare-styleable> resources to your project. Habitually put these <declare-styleable> resources into a res/values/attrs. xml file. The following is an example of attrs. xml:
<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 code above declares two custom attributes, that is
Showtext and labelposition, both attributes belong to a styleable object named piechart. By convention, the styleable object name should be the same as the class name of the custom View class. Although this does not strictly require you to follow this Convention, many popular buy-on-demand editors rely on this naming convention to provide code prompts.
Once you customize attributes, you can
File. The only difference is that your custom attributes belong to a different namespace. They are not
Package name], for example, how to use these attributes to declare piechart

<?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>

To avoid having to use a long namespace URI, this example uses an xmlns indicator that assigns an alias custom to the namespace http://schemas.android.com/apk/res/com.example.customviews, you can use any alias for your namespace. Note: The name of the XML tag that adds a custom View to the layout. It fully limits the name of the custom View class. If your view class is an internal class, you need to further limit it through the external Class Name of the view. Further, for example, this piechart class has an internal class pieview. To use custom attributes, you should use the tag com. example. customviews. charting. piechart $ pieview. Custom Attributes of an application
When a view is created from an XML layout, all attributes in the XML tag are read from the resource bundle and used asAttributeset objectPassed to the View class constructor. Although the value can be directly read from the attributeset object, there are some disadvantages to doing so:

  • The resource reference of the property value has not been resolved.
  • Style not applied
You can set AttributeSetPass obtainStyledAttributes()This method returns a referenced and added Style TypedArrayArray value.
The android resource compiler does a lot for you to make it easier to call obtainstyledattributes (). For each <declare-styleable> resource, a set of attribute IDs and constants defining each element index in the array are generated in the R. Java file. You use predefined constants TypedArrayRead attribute values in the object. The following is an example of the piechart class reading its attribute values:
public PieChart(Context context, AttributeSet attrs) {   super(context, 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 This
TypedArray
The object is a shared resource and needs to be recycled after use (recycle)
Adding attributes and event attributes is a powerful way to control the behavior and interface of views, but they can only be read during view initialization. To provide dynamic behavior, the getter and setter methods of each custom attribute must be displayed. The following code snippet shows how piechart exposes the showtext attributes:

public boolean isShowText() {   return mShowText;}public void setShowText(boolean showText) {   mShowText = showText;   invalidate();   requestLayout();}

Note that the invalidate () and requestlayout () methods are called in setshowtext. These calls are crucial to ensure the view behavior is reliable. After any attribute that may change the view appearance is sent and changed, you must invalidate
View, so that the system knows that it needs to be re-drawn. Similarly, if an attribute that may affect the size or shape of the view changes, you need to request a new layout. Forgetting to call these two methods will cause some bugs that are hard to find. Custom views should also support event listening to convey important events. For example, piechart providesOncurrentitemchangedCustom events to notify the listener that the user has rotated the pie chart to focus on the new pie chart. It is easy to forget to provide attributes and events, especially when you only use custom views. Please take some time to carefully define your interface to reduce the overhead for future maintenance. A good rule that can be followed is to always provide features that can affect the shape or behavior of custom views. Custom views designed for the experience should support a wide range of users, including those who are invisible or untouchable. To support these users with disabilities, you should:

  • Use the Android: contentdescription attribute to mark your input box
  • CallsendAccessibilityEvent()Method To send accessible events
  • Support for standby controllers, such as D-pad and trackball
For more information about creating accessible views, refer to making in the android developer guide.
Applications accessible

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.