`

[AndroidTips]Declaring a custom android UI element using XML

 
阅读更多

 

 

http://stackoverflow.com/questions/2695646/declaring-a-custom-android-ui-element-using-xml

 

The Android Developer Guide has a section called Building Custom Components . Unfortunately, the discussion of XML attributes only covers declaring the control inside the layout file and not actually handling the values inside the class initialisation. The steps are as follows:

1. Declare attributes in values\attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyCustomView">
        <attr name="android:text"/>
        <attr name="android:textColor"/>            
        <attr name="extraInformation" format="string" />
    </declare-styleable>
</resources>
 

Notice the use of an unqualified name in the declare-styleable tag. Non-standard android attributes like extraInformation need to have their type declared. Tags declared in the superclass will be available in subclasses without having to be redeclared.

2. Create constructors

Since there are two constructors that use an AttributeSet for initialisation, it is convenient to create a separate initialisation method for the constructors to call.

private void init(AttributeSet attrs) { 
    TypedArray a=getContext().obtainStyledAttributes(
         attrs,
         R.styleable.MyCustomView);

    //Use a
    Log.i("test",a.getString(
         R.styleable.MyCustomView_android_text));
    Log.i("test",""+a.getColor(
         R.styleable.MyCustomView_android_textColor, Color.BLACK));
    Log.i("test",a.getString(
         R.styleable.MyCustomView_android_extraInformation));

    //Don't forget this
    a.recycle();
}
 

R.styleable.MyCustomView is an autogenerated int[] resource where each element is the ID of an attribute. Attributes are generated for each property in the XML by appending the attribute name to the element name. Attributes can then be retrieved from the TypedArray using various get functions. If the attribute is not defined in the defined in the XML, then null is returned. Except, of course, if the return type is a primitive, in which case the second argument is returned.

If you don't want to retrieve all of the attributes, it is possible to create this array manually.The ID for standard android attributes are included in android.R.attr , while attributes for this project are in R.attr .

int attrsWanted[]=new int[]{android.R.attr.text, R.attr.textColor};
 

Please note that you should not use anything in android.R.styleable , as per this thread it may change in the future. It is still in the documentation as being to view all these constants in the one place is useful.

3. Use it in a layout files such as layout\main.xml

Include the namespace declaration xmlns:app="http://schemas.android.com/apk/res/com.mycompany.projectname" in the top level xml element.

<com.mycompany.projectname.MyCustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:text="Test text"
    android:textColor="#FFFFFF"
app:extraInformation="My extra information";
/> 
 

Reference the custom view using the fully qualified name.

Android LabelView Sample

If you want a complete example, look at the android label view sample.

LabelView.java

TypedArray a=context.obtainStyledAttributes(attrs, R.styleable.LabelView);
 CharSequences=a.getString(R.styleable.LabelView_text);

attrs.xml

<declare-styleable name="LabelView">
    <attr name="text"format="string"/>
    <attr name="textColor"format="color"/>
    <attr name="textSize"format="dimension"/>
</declare-styleable>

custom_view_1.xml

<com.example.android.apis.view.LabelView
    android:background="@drawable/blue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    app:text="Blue"app:textSize="20dp"/>

This is contained in a LinearLayout with a namespace attribute: 

xmlns:app="http://schemas.android.com/apk/res/com.example.android.apis"

Links

 
分享到:
评论

相关推荐

    Android Application Security Essentials

    Product discovery using a mobile device 172 Mobile payments 173 Configurations 173 PCI Standard 175 Point of Sale 176 Proximity technologies 178 Social networking 178 Table of Contents [vi ] ...

    professional.Android.Application.Development.2009.pdf

    Using a Bluetooth Headset 344 Managing Network and Wi-Fi Connections 345 Monitoring and Managing Your Internet Connectivity 345 Managing Active Connections 346 Managing Your Wi-Fi 347 ...

    Manning.Spring.in.Action.4th.Edition.2014.11.epub

    7.1.3. Declaring DispatcherServlet in web.xml 7.2. Processing multipart form data 7.2.1. Configuring a multipart resolver 7.2.2. Handling multipart requests 7.3. Handling exceptions 7.3.1. Mapping ...

    Android代码-WebArchiveReader

    This web archive file is actually an XML file with the contents of the page encoded in Base64 format, and also contains all sub-frames and objects embedded into a page, such as images etc. Please ...

    Windows Presentation Foundation

    Programming Windows Presentation Foundation By Ian Griffiths, Chris Sells ... an XML-based markup language (XAML) for declaring the structure of your Windows UI; and a radical new model for controls

    Servlets和JSP核心技术 卷2(英文版) 第一部分

    Using Ant to Build a Web Application Section A.7. Example: Building a Web Application Section A.8. Using Ant to Create a WAR File Section A.9. Example: Creating a Web Application WAR File Index

    Servlets和JSP核心技术 卷2(英文版) 第二部分

    Using Ant to Build a Web Application Section A.7. Example: Building a Web Application Section A.8. Using Ant to Create a WAR File Section A.9. Example: Creating a Web Application WAR File Index

    实验三:数组及其应用.doc

    3. The third program finds the maximum element in a 2D array and prints its position and value. 4. The fourth program concatenates two strings using the `strcat` function. 5. The fifth program ...

    thymeleaf-extras-eclipse-plugin-2.1-master.zip

    The content assist features are driven by metadata about a dialect, currently done using XML files, conforming to a schema that lives at http://www.thymeleaf.org/xsd/thymeleaf-extras-dialect-2.1.xsd. ...

    JSP Simple Examples

    Calculate a factorial by using while loop In this example we are going to find out the factorial of 12 by using the while loop. In while loop the loop will run until the condition we have given gets ...

    AndroidStudio Gradle文件

    source build automation system that builds upon the concepts of Apache Ant and Apache Maven and introduces a Groovy-based domain-specific language (DSL) instead of the XML form used by Apache Maven ...

    ZendFramework中文文档

    14.5.1. Declaring Filter and Validator Rules 14.5.2. Creating the Filter and Validator Processor 14.5.3. Retrieving Validated Fields and other Reports 14.5.3.1. Querying if the input is valid 14.5...

    DWR.xml配置文件说明书(含源码)

    如果远程Bean A有个方法A.blah(B),那么你需要为A建立一个created,为B建立一个converted. 配置文件init部分声明那些用于建立远程bean和在方法调用中转换bean的类.这部分是可选择性配置的,多数情况下可以不必使用它,...

    Apache Geronimo 2.1_ Quick Reference.pdf

    Using a database pool in an application 70 Accessing a server-scoped database pool 70 Accessing an application-scoped database pool from the same application 74 Accessing an application-scoped ...

    Winform和net的结合

    In order to use this function, all you have to do is provide a valid HINTERNET handle obtained using a standard InternetOpen() call. If you want, you can provide a handle to a progress window (and an...

    IOS5 Programming Cookbook

    Based on the provided information from "iOS 5 Programming Cookbook" by Vandad Nahavandipoor, we can derive a comprehensive set of knowledge points related to iOS development using Objective-C....

Global site tag (gtag.js) - Google Analytics