类型描述 | 字段名称 | 定义方式举例 | 调用方式举例 |
---|---|---|---|
资源ID |
reference |
|
|
颜色 | color |
|
|
布尔值 | boolean |
|
|
尺寸值 | dimension |
|
|
浮点值 | float |
|
|
整数型 | integer |
|
|
字符串 |
string |
|
|
百分比 | fraction |
|
|
枚举类型 |
enum |
|
|
位或运算 | flag |
|
|
附加:自定义xml属性步骤
1、在res/values/目录中新建resources的xml文件,xml举例:
<resources>
<declare-styleable name="accItem">
<attr name="accleftimg" format="reference"/>
<attr name="acctitle" format="string"/>
<attr name="splitstyle_top">
<enum name="none_line" value="0"/>
<enum name="whole_line" value="1"/>
<enum name="half_line" value="2"/>
</attr>
<attr name="splitstyle_bottom">
<enum name="none_line" value="0"/>
<enum name="whole_line" value="1"/>
<enum name="half_line" value="2"/>
</attr>
</declare-styleable>
</resources>
-
declare-styleable:自定义属性块标识
-
accItem:自定义属性块的名称,在代码获取xml属性的时候会使用到
-
<attr>:一项自定义属性的标识块,其中name为属性名称,format为属性格式,参考起始表
2、在xml文件中如何使用
-
在xml定义xmlns,举例示意:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/package"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
代码第二行即为我们自定义的xmlns,有三点需要注意:1、xmlns为定义xmlns标识,不可改变;2、app(xmlns:app)为引用标识,用户可自行改变,使用xml布局时,使用该标识可指定属性,如“app.acctitle = "demo"”;3、package是可变参数,必须于工程项目的包名相同,即"AndroidManifest.xml"中的package
-
布局文件中使用自定义控件的时候,和嵌入普通布局一样,引用属性时,使用上一步定义的xmlns加第一步时定义的attr->name直接使用。举例说明:
<!--自定义控件--> <package.view.demo android:layout_width="match_parent" android:layout_height="wrap_content" <!--app为我们定义的xmlns--> <!--app后的属性已在declare-styleable中定义--> app:accleftimg="@drawable/gerenziliaoimg" app:acctitle="@string/gerenziliao" app:splitstyle_top="whole_line" app:splitstyle_bottom="half_line" > </package.view.demo>
参考代码:3、如何在自定义控件中获取自定义属性的值
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.accItem); mheaderDrawable = a.getDrawable(R.styleable.accItem_accleftimg); mcontentTitle = a.getString(R.styleable.accItem_acctitle); mtopSpliterStyle = a.getInt(R.styleable.accItem_splitstyle_top, 0); mbottomSpliterStyle = a.getInt(R.styleable.accItem_splitstyle_bottom, 0); a.recycle();
第一行:R.styleable.accItem,其中accItem为在资源文件中定义的declare-styleable代码块的name属性使用TypedArray 获取自定义属性
第二行:R.styleable.accItem_accleftimg,其中accItem_accleftimg为[declare-styleable][name]->[attr][name]属性
第三行:执行完毕后,需要调用recycle来释放元素