自定义布局之TypedArray类

一些项目需求,需要自定义属性,也就是在values 的文件夹下面新建 attrs.xml 文件。会配置一些属性。使用属性时就遇到了 TypedArray 类的使用。以前没有使用过,也就没深入研究,今天遇到了,就百度了一下。也算有所了解。首先创建 attrs.xml文件。

1
2
3
4
5
6
7
8
9
10
11
<?xml version= "1.0" encoding= "utf-8" ?>
<resources>
     <declare-styleable name= "RainView" >
         <attr name= "rainNum" format= "integer" />
         <attr name= "size" format= "integer" />
         <attr name= "rainColor" format= "integer" />
         <attr name= "randColor" format= "boolean" />
     </declare-styleable>
     
</resources>

可以看到,定义了四个属性。首先在布局文件中,这里说的是自定义组件的时候,在布局文件的顶部加上这一句话:

1
2
3
4
5
6
<RelativeLayout xmlns:android= "http://schemas.android.com/apk/res/android"
     xmlns:tools= "http://schemas.android.com/tools"
     android:id= "@+id/container"
     android:layout_width= "match_parent"
     android:layout_height= "match_parent" >

可以看到这是布局的根节点,比平时的布局文件多了一行代码:

这是项目的包名。而自定义控件设置属性时,如下:

1
2
3
4
5
6
7
8
<com.jikexueyuan.rain.v2.RainView
      android:layout_width= "match_parent"
      android:layout_height= "match_parent"
      android:background= "#ff000000"
      rain:rainColor= "0xff00ff00"
      rain:rainNum= "50"
      rain:randColor= "true"
      rain:size= "20" />

而在代码中需要,改变属性时怎么操作呢,也是代码如下:

1
2
3
4
5
6
7
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.RainView);
    rainNum = ta.getInteger(R.styleable.RainView_rainNum, 80 );
    size = ta.getInteger(R.styleable.RainView_size, 20 );
    rainColor = ta.getInteger(R.styleable.RainView_rainColor, 0xffffffff );
    randColor = ta.getBoolean(R.styleable.RainView_randColor, false );
      
   ta.recycle();

你会发现,TypedArray 类就用到了。 在引用时,还需要,注意的是:R.styleable.RainView, 而 设置属性时是这样的:R.styleable.RainView_randColor ,这是固定的命名方式。至此,TypedArray 类就讲完了。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值