android的自定义属性

感觉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”的各种方法来获取相应的属性值。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值