Android自定义属性时typedArray的使用方法

自己定义的布局,需要自己自定义view,通常继承View然后重写构造方法以及onDraw等函数。同时,我们也可以自定义属性。步骤如下:

  1. 在项目文件res/value下面创建一个attr.xml文件,该文件包含若干个attr的集合,如:

<Resources> 

   <declare-styleable name="MyView">  

        <attr name="myTextSize"format="dimension"/>  

        <attr name="myColor"format="color"/>  

   </declare-styleable>  

</Resources> 

其中resource是根标签,可以在里面定义若干个declare-styleable<declare-styleable name=myView> name定义了变量名称,下面可以再定义多个属性,针对<attr name=myTextSize format=dimension/>来说,其属性的名称为”myTextSize,format指定了该属性类型为dimension,只能表示字体的大小。

Format还可以指定其他的类型,比8如:

Reference 表示引用,参考某一资源的ID

String 表示字符串

Color 表示颜色值

Dimension 表示尺寸值

Boolean表示布尔值

Integer 表示整型值

Float 表示浮点值

Fraction 表示百分数

Enum 表示枚举值

Flag 表示位运算

2.在使用该自定义view的布局文件中加入如下一行:

   xmlns :app=http://schemas.android.com/apk/res/com...   注意(后面的com.什么为activity的包名)

3.在自定义view的代码中引入自定义属性。修改构造函数

Context通过调用obtainStyledAttributes方法来获取一个TypeArray,然后又该TypeArray来对属性进行设置,

obtainStyledAttributes方法有三个,我们常用的是有一个参数的obtainStyledAttributes(int[]  attrs),其参数直接styleable中获得。

TypedArray a = context.obtainStyledAttributes(attrs ,R.Styleable.MyView);

调用结束后务必调用recycle()方法。否则这次的设定会影响下次的使用。

 

注意:属性定义时可以指定多种类型值:

1.属性定义:

<declare-styleable name=名称”>

   <attr name=background format=reference|color/>

</declare-styleable>

2.属性使用:

<ImageView

   android:layout_width = 42dip

   android:layout_height=42dip

   android:background=@drawable/图片id|颜色#。。。”/>



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值