Use of custom attributes for Android

Source: Internet
Author: User

1. Customize a View File myview. Java

2. Define the custom property file values/attrs. xml

<? XML version = "1.0" encoding = "UTF-8"?>
<Resources>
<Declare-styleable name = "myatrr">
<ATTR name = "textcolor" format = "color"/>
<ATTR name = "textsize" format = "dimension"/>
</Declare-styleable>
</Resources>

3. Use custom views and attributes in the main layout File

Xmlns: MySpace = "http://schemas.android.com/apk/res/com.example.attrtest" // Add namespace, red for package name

<Com. example. attrtest. myview
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
MySpace: textsize = "25dp"
MySpace: textcolor = "# ff00ff00"
/>

Note: When textcolor is assigned, it is an 8-bit value. Otherwise, it will fail to be obtained in the program.

4. Get the custom attribute when the custom view is initialized

When the custom view is initialized in the layout file, the constructor of two parameters is called.

Typedarray TA = context. obtainstyledattributes (attrs, R. styleable. myatrr );
Int textcolor = TA. getcolor (R. styleable. myatrr_textcolor, color. Red );
Float textsize = TA. getdimension (R. styleable. myatrr_textsize, 30 );

The second parameter of both functions is the default value given when no custom attribute is added.

That's simple.

Source code: http://download.csdn.net/detail/wulongtiantang/5134371

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.