自定义属性 自定义属性 1
命名空间 2 1.1. 什么是命名空间 2 1.2. android命名空间 2 1.3. 自定义命名空间 2配置文件(attrs.xml) 3 2.1. Android的配置文件 3 2.2. 自定义配置文件 4获取属性 4 3.1. 1.设置好命名空间 4 3.2. 2.设置自定义命名空间自定义属性值 4 3.3. 3.通过重写View中的Context和AttributeSet参数的构造函数 4 3.4. 4.通过AttributeSet该参数获取对应的属性值 4 命名空间 1.1. 什么是命名空间 XML命名空间提供避免元素冲突的方法 1.2. android命名空间xmlns:android=”http://schemas.android.com/apk/res/android
xmlns:前缀 android:名称,可以自定义 url:代表的就是空间,是个没有用的url,是统一资源标识符,相对于一个常量 1.3. 自定义命名空间
xmlns:空间名称="http://schemas.android.com/apk/res-auto
操作演示:
配置文件(attrs.xml)2.1. Android的配置文件 配置文件如下: declare-styleable name:属性集合名称 attr name:属性名称 format:格式
共11种格式 1.reference(资源id) <ImageView android:background = "@drawable/图片ID"/> 2.color <TextView android:textColor = "#00FF00" /> 3.boolean 4.dimension(尺寸)(dp) 5.float(浮点值) 6.integer(整形值) 7.string(字符串) 8.fraction(百分比) 9.enum(枚举值) <declare-styleable name="名称"> <attr name="orientation"> <enum name="horizontal" value="0" /> <enum name="vertical" value="1" /> </attr> </declare-styleable> 10.flag(位或运算) 注意:位运算类型的属性在使用的过程中可以使用多个值 11.混合属性(使用|分开多个属性)2.2. 自定义配置文件 以TextView为例 3. 获取属性
3.1. 1.设置好命名空间 3.2. 2.设置自定义命名空间自定义属性值 3.3. 3.通过重写View中的Context和AttributeSet参数的构造函数 3.4. 4.通过AttributeSet该参数获取对应的属性值
方法一: 通过方法获取值
方法二: TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attrs, R.styleable.DrawLine); index = obtainStyledAttributes.getInteger(R.styleable.DrawLine_line_type, 0); 这边的R.styleable.DrawLine_line_type就是我们自定义的内容
更多详细参考:https://www.jianshu.com/p/05ccc62bebbf