Steps for customizing controls in Android

Source: Internet
Author: User

Android Development will inevitably encounter the need to customize the control needs, some of the product requirements in the Android standard Control Library does not meet the requirements, some of the development process without the code can be reused, their own definition.


a good custom control should be like the controls provided by Android itself, encapsulating a range of features for developers to use, not only for complete functionality, but also for efficient use of memory and CPUs. Android itself provides a
Some indicators:
1. Specifications for Android standards (naming, configurable, event handling, etc.) should be adhered to.
2. In the XML Layout section, configure the properties of the control.
3. The interaction should have the appropriate feedback, such as press, click And so on.
4. Compatibility, many Android versions, should have a wide range of applicability.


Android has provided a series of underlying controls and XML attributes to help you create custom controls.

1. Sub-class of view

View is one of the most basic controls in Android, and all controls inherit from view, and you can inherit the view directly or inherit other controls such as ImageView.


of course, you need to provide at least one constructor, with context and attributeset as arguments. Examples are as follows:

Class Piechart extends View {public    Piechart (context context, AttributeSet Attrs) {        Super (context, attrs);    }}


2. Custom Attributes

a perfect custom control can also add XML to configure properties and styles. To achieve this, you can do this by following these steps:
1) Add custom properties <declare-styleable> to XML file
2) in XML <declare-styleable>, specify the value of the attribute
3) Get the values in the XML in the view
4) Apply the acquired value to the view


The following continues to illustrate:
add <declare-styleable> to your program, it's customary to put it in a res/values/attrs.xml file, for example:
<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>



This code declares two custom properties Showtext and LabelPosition, which belong to a custom entity piechat.


Once you have defined the properties, you can use them in XML, and here's a simple example:


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


As can be seen with standard Android components, the only difference is that they belong to different namespaces, the standard component namespace is generally http://schemas.android.com/apk/res/android,

Our custom namespace is Http://schemas.android.com/apk/res/[your package name]. Have you noticed the custom in the Xmlns:custom? You can use any of the characters, but
to be consistent with the characters in the definition of the following control.
Another thing to note is that the Tag:com.example.customviews.charting.PieChart in XML requires the full package name, if your custom control is an inner class (well, so wonderful),
You must also give the full path, assuming that Piechat has an inner class pieview, and if you reference it in XML, you need to use this: Com.example.customviews.charting.piechart$pieview


3) Apply a custom property value
When view is created, all of the attributes defined in the XML can be read by AttributeSet, and the attrs is read through Obtainstyledattributes in the constructor ,
the method returns a Typearray array. By Typearray, you can read a method that is already defined in XML. The following example shows the value of the XML attribute read above.

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 ();   }}


It should be emphasized that the typearray need to be destroyed after use, or memory leaks will occur.

4) Adding custom methods and Events
The custom attribute is powerful, but the disadvantage is obvious, it can only be applied to the control when the view is initialized. To add more flexible behavior, you can add getter and setter for each property
That 's right. The following code snippet shows the properties of the Piechat Showtext
public Boolean Isshowtext () {   return mshowtext;} public void Setshowtext (Boolean showtext) {   mshowtext = Showtext;   Invalidate ();   Requestlayout ();}


invalidate () and requestlayout () are called in Setshowtext to ensure that the view can be updated in a timely manner. In your custom view, if a property is changed and requires immediate effect,
You must also call this method. The system will then redraw the view immediately. Similarly, if the size or shape of the view changes, you must also call Requestlayout (). Otherwise it will cause
a lot of problems.

In general you also need to add event callbacks to communicate with callers. For example, Piechat exposes oncurrentitemchanged to inform the caller that pie chat has rotated.
In the development process, it is easy to forget to add some properties and events, especially when the author is the only user of this custom view. In order to make the view more universal, it should take some time to consider it more comprehensively.
you'd better be exposed to all the properties that might change appearance and behavior. Of course, this also makes a higher request to you, otherwise how to enter not.













































Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Steps for customizing controls in Android

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.