Android custom View (1)

Source: Internet
Author: User

1. Custom View class inherits the subclass of View or View

All of the view classes defined in the Android framework extendView. Your custom view can also extendViewDirectly, or you can save time by extending one of the existing view subclasses, suchButton.

To allow the Android Developer Tools to interact with your view, at a minimum you must provide a constructor that takesContextAndAttributeSetObject 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);    }}


Ii. Custom Attributes

  • Define custom attributes for your view in Resource element
  • Specify values for the attributes in your XML layout
  • Retrieve attribute values at runtime
  • Apply the retrieved attribute values to your view

    To define custom attributes, add Resources to your project. It's customary to put these resources intores/values/attrs.xmlFile. Here's an example ofattrs.xmlFile:

          
                                 
                    
                   
        
       
    This code declares two custom attributes,showTextAndlabelPosition, That belong to a styleable entity namedPieChart. The name of the styleable entity is, by convention, the same name as the name of the class that defines the custom view. although it's not strictly necessary to follow this convention, too popular code editors depend on this naming convention to provide statement completion.

    Once you define the custom attributes, you can use them in layout XML files just like built-in attributes. the only difference is that your custom attributes belong to a different namespace. instead of belonging tohttp://schemas.android.com/apk/res/androidNamespace, they belonghttp://schemas.android.com/apk/res/[your package name]. For example, here's how to use the attributes definedPieChart:

    In order to avoid having to repeat the long namespace URI, the sample usesxmlnsDirective. This directive assigns the aliascustomTo the namespacehttp://schemas.android.com/apk/res/com.example.customviews. You can choose any alias you want for your namespace.

    Notice the name of the XML tag that adds the custom view to the layout. it is the fully qualified name of the custom view class. if your view class is an inner class, you must further qualify it with the name of the view's outer class. further. for instance,PieChartClass has an inner class calledPieView. To use the custom attributes from this class, you wocould use the tagcom.example.customviews.charting.PieChart$PieView.

    3. Use Custom Attributes

    When a view is created from an XML layout, all of the attributes in the XML tag are read from the resource bundle and passed into the view's constructor asAttributeSet. Although it's possible to read values fromAttributeSetDirectly, doing so has some disadvantages:

    • Resource references within attribute values are not resolved
    • Styles are not applied

      Instead, passAttributeSetToobtainStyledAttributes(). This method passes backTypedArrayArray of values that have already been dereferenced and styled.

      The Android resource compiler does a lot of work for you to make callingobtainStyledAttributes()Easier. For each Resource in the res directory, the generated R. java defines both an array of attribute ids and a set of constants that define the index for each attribute in the array. you use the predefined constants to read the attributes fromTypedArray. Here's howPieChartClass reads its attributes:

      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 thatTypedArrayObjects are a shared resource and must be recycled after use.

      4. Add Properties and Events

      Attributes are a powerful way of controlling the behavior and appearance of views, but they can only be read when the view is initialized. to provide dynamic behavior, expose a property getter and setter pair for each custom attribute. the following snippet shows howPieChartExposes a property calledshowText:

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

      Notice thatsetShowTextCILSinvalidate()AndrequestLayout(). These CILS are crucial to ensure that the view behaves reliably. you have to invalidate the view after any change to its properties that might change its appearance, so that the system knows that it needs to be redrawn. likewise, you need to request a new layout if a property changes that might affect the size or shape of the view. forgetting these method CILS can cause hard-to-find bugs.

      Custom views shoshould also support event listeners to communicate important events. For instance,PieChartExposes a custom event calledOnCurrentItemChangedTo define y listeners that the user has rotated the pie chart to focus on a new pie slice.

      It's easy to forget to expose properties and events, especially when you're the only user of the custom view. taking some time to carefully define your view's interface CES future maintenance costs. A good rule to follow is to always expose any property that affects the visible appearance or behavior of your custom view.

      V. Design For Accessibility

      Your custom view shocould support the widest range of users. This includes des users with disabilities that prevent them from seeing or using a touchscreen. To support users with disabilities, you shoshould:

      • Label your input fields usingandroid:contentDescriptionAttribute
      • Send accessibility events by callingsendAccessibilityEvent()When appropriate.
      • Support alternate controllers, such as D-pad and trackball

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.