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文件中调用。
那是否可以在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值。
也可以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的简单使用。