Android TypedArray的用法

Android TypedArray的用法

在项目中经常会有自定义组件的情况,为了方便组件可以在多个地方独立使用,我们最常用的是setXX()方法。
那是否可以在XML布局文件调用时就可以设备自定义组件的各个属性呢,这个是可以有的,Android提供了TypedArray。
下面介绍一下TypedArray在项目的实际用法:
1,在attrs.xml文件中定义。
   <?xml version="1.0" encoding="utf-8"?>
   <resources>
   
    <declare-styleable name="styleable_name">
       
        <attr name="attr_name" format="reference|color" />
       
    </declare-styleable>
    <resources>
 
 
2,在自定义组件中调用(在构造函数中调用)。
  
   public CustomizeView(Context context, AttributeSet attrs, int defStyle){
  TypedArray mTypedArray = context.obtainStyledAttributes(attrs,R.styleable.styleable_name);
  int color = mTypedArray.getColor(R.styleable.styleable_name_attr_name, Color.GREEN);
   }

  
3, 在XML文件中调用。

     <package_name.CustomizeView
     xmlns:android_custom = "http://schemas.android.com/apk/res/app_package_name"   
    android:id="@+id/round_progressbar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android_custom:attr_name="@color/transparent"
    />
  
   xmlns:android_custom = "http://schemas.android.com/apk/res/app_package_name"这句是必不可少的。android_custom代表调用时的前缀,
   可以自定义名字app_package_name是应用的包名
  也可以xmlns:android_custom = "http://schemas.android.com/apk/res-auto"替换成这样更加方便。
  
  android_custom:attr_name="@color/transparent"就表示在配置中设定attr_name的值。因为<attr name="attr_name" format="reference|color" />
  这里的format="reference|color"表示引用或都color,所以在XML中android_custom:attr_name对应的值也要是color值。

  
以上3个步骤,就完成了对TypedArray的简单使用。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值