zoukankan      html  css  js  c++  java
  • Android define attribute

    1、values目录中定义一个attrs.xml
    
        Format:
            <declare-styleable name="">
                <attr name="" format="" />
            </declare-styleable>
            
        name 自定义
        
        format值
            1.reference:参考指定Theme中资源ID,这个类型意思就是你传的值可以是引用资源
            2.string:字符串,如果你想别人既能直接写值也可以用类似"@string/test"引用资源的方式,可以写成format="string|reference"
            3.Color:颜色
            4.boolean:布尔值
            5.dimension:尺寸值
            6.float:浮点型
            7.integer:整型
            8.fraction:百分数
            9.enum:枚举 ,如果你提供的属性只能让别人选择,不能随便传入,就可以写成这样
                <attr name="language">
                    <enum name="Cn" value="1" />
                    <enum name="En" value="2" />
                </attr>
            10.flag:位或运算
    2、取得自定义属性值的方法
        /*
         * API中的方法
         * android.content.Context
         */
        TypedArray Context.obtainStyledAttributes(int[] attrs)
        TypedArray Context.obtainStyledAttributes(int resid, int[] attrs)
        TypedArray Context.obtainStyledAttributes(AttributeSet set, int[] attrs)
        TypedArray Context.obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
            
        TypedArray.getXX();        // 取属性的方法
        TypedArray.recycle();      // 释放资源
    3、在Layout布局中使用
    
        //命名空间写法:
        {
            xmlns:空间名="http://schemas.android.com/apk/res/包名"
            // 空间名:自定义,与其他别的属性没有什么关联性
            // 包名:与Manifest中package的值保持一致
        }
        
        Example:
            <!-- 假设包名为 com.miles.apk -->
            <!-- attrs.xml -->
            <?xml version="1.0" encoding="utf-8"?>
            <resources>
                <declare-styleable name="defName">
                        <attr name="attr" format="integer" />
                </declare-styleable>
            </resources>
            
            <!-- layout.xml -->
            <?xml version="1.0" encoding="utf-8"?>
            <LinearLayout 
                xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:defattrs="http://schemas.android.com/apk/res/com.miles.apk"
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"    >
                <!--
                DView表示自定义的View
                在自定义的View中取得自定义属性值,请参考2
                -->
                <DView
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    defattrs:attr="1" />
            </LinearLayout>

    PS:关于format值的介绍来自网上搜索

  • 相关阅读:
    【转】Java学习---HashMap的工作原理
    【转】Java学习---集合框架那些事
    Linux学习---linux下的彩蛋和各种有趣的命令
    【转】VMware虚拟机三种网络模式超详解
    沃顿商学院的MBA课程
    本杰明-富兰克林的13节制
    美学需要读的书
    芒格推荐书单
    回声消除(AEC)原理
    adc0和adc1
  • 原文地址:https://www.cnblogs.com/smile365/p/3198283.html
Copyright © 2011-2022 走看看