简单的自定义XML属性

2016-08-10 / 15 阅读 / Android

1、 属性定义
在res\values文件夹下新建attrs.xml文件。当然也可以在任意<resources>根下去定义属性。为了统一,还是新建attrs来的清楚。

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<declare-styleable name="MyView">
		<attr name="customnAttr" format="integer"></attr>
	</declare-styleable>
</resources>

定义方式很容易理解
declare-styleable表示一个属性组的根节点
name表示该属性组的名称
attr节点表示属性
attr的name表示该属性的名称
format表示该属性可以接受的值(字符,资源,小数,布尔值...)

 

2、 使用
使用方式很简单
布局文件添加

   xmlns:app="http://schemas.android.com/apk/res-auto"

这里 app可以任意(除了android) ,res-auto也可替换为具体定义该属性的apk的包名

 

    <com.example.yisd.myapplication.MyView
        app:customnAttr="3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

app:customnAttr="3"这里使用的就是我们自定义的属性。

3、 获取
以上的步骤只是定义和使用了,但是是没有效果的。
想要效果需要在对应的自定义类中来处理

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        int anInt = typedArray.getInt(R.styleable.MyView_customnAttr, 1);
        typedArray.recycle();

    }

处理步骤非常简单
获取配置-->获取定义的属性-->自定处理-->结束销毁

相关推荐