您的位置:首页 > 移动开发 > Android开发

android的自定义属性

2015-10-10 14:49 429 查看
感觉android官方定义的组件不够用时,可以选择自定义组件,自定义组件通常分为3步,

第一步:在res/values文件下定义一个diy.xml文件,代码如下。

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ToolBar">
<attr name="buttonNum" format="integer"/>
<attr name="itemBackground" format="reference|color"/>
</declare-styleable>
</resources>


该文件是定义属性名和格式的地方,需要用到<declare-styleable
name="ToolBar"> </declare-styleable>包围所有属性。其中name为该属性集的名字,主要用途是标识该属性集。在第三步获取某属性标识时,会用到该属性集名字,例如:“R.styleable.ToolBar_buttonNum”,

而类似
<attr name="buttonNum" format="integer"/>


则为属性名以及属性的类型,亦有
<attr name="testEnum">
<enum name="fill_parent" value="-1"/>
<enum name="wrap_content" value="-2"/>
</attr>


这种形式

第二步:在布局文件xml中使用该属性。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:toolbar="http://schemas.android.com/apk/res/cn.zzm.toolbar"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<cn.zzm.toolbar.ToolBar android:id="@+id/gridview_toolbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@drawable/control_bar"
android:gravity="center"
toolbar:buttonNum="5"
toolbar:itemBackground="@drawable/control_bar_item_bg"/>
</RelativeLayout>


注意要先声明:
xmlns:toolbar="http://schemas.android.com/apk/res/cn.zzm.toolbar"


前面的toolbar可以换成任意字符,但是后面的url地址最后一部分需用上包名。

在android studio中会出现无法识别的问题,需要替换成

xmlns:toolbar="http://schemas.android.com/apk/res-auto"
的形式

第三步:在自定义组件中,可以如下获得xml中定义的值

TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ToolBar);
buttonNum = a.getInt(R.styleable.ToolBar_buttonNum, 5);
itemBg = a.getResourceId(R.styleable.ToolBar_itemBackground, -1);

a.recycle();
在自定义组件的构造函数中,用
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ToolBar);
获得对属性集的引用,然后即可用“a”的各种方法来获取相应的属性值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: