Android自定义属性

主要步骤:

1.在values文件夹中创建一个attrs.xml文件.

如:
<resources>

    <!-- 声明属性集的名称-->
    <declare-styleable name="ToggleButton">

        <!-- 声明一个属性 name 是my_background   类型为 引用类型 引用资源ID-->
        <attr name="my_background" format="reference"/>

        <!-- 声明一个属性 name my_slideButton   类型为 引用类型 引用资源ID-->
        <attr name="my_slideButton" format="reference"/>

        <!-- 声明一个属性 name curr_state   类型为 boolean类型-->
        <attr name="curr_state" format="boolean"/>

    </declare-styleable>

</resources>


2.布局文件中使用新属性,使用之前必须先声名命名空间.

1
xmlns:curson="http://schemas.android.com/apk/res-auto"
1
2
3
4
5
6
7
8
9
<com.curson.togglebutton.ToggleButton
xmlns:curson="http://schemas.android.com/apk/res-auto"
android:id="@+id/togglebutton"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
curson:my_background="@mipmap/switch_background"
curson:my_slideButton="@mipmap/slide_button"
curson:curr_state="false"/>

3.在自定义view的构造方法中,通过解析AttributeSet对象,获得所需要的属性值.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public ToggleButton(Context context, AttributeSet attrs) {
super(context, attrs);
//获得自定义属性
@SuppressLint("Recycle")
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ToggleButton);
int indexCount = typedArray.getIndexCount();
for (int i = 0; i < indexCount; i++) {
/**
* 获取某个属性的ID值
*/
int index = typedArray.getIndex(i);
switch (index) {
case R.styleable.ToggleButton_curr_state:
currentState = typedArray.getBoolean(index, false);
case R.styleable.ToggleButton_my_background:
backgroundId = typedArray.getResourceId(index, -1);
if (backgroundId == -1) {
throw new RuntimeException("请设置背景图片");
}
slideBackgroundBitmap = BitmapFactory.decodeResource(getResources(), backgroundId);
break;
case R.styleable.ToggleButton_my_slideButton:
slideButtonId = typedArray.getResourceId(index, -1);
if (slideButtonId == -1) {
throw new RuntimeException("请设置按钮图片");
}
slideButton = BitmapFactory.decodeResource(getResources(), slideButtonId);
break;
}
}
}

format 常用类型:

enmu       枚举值

color       颜色

float       浮点值

string     字符串

boolean    布尔值

integer    整型值

reference  引用

dimension  尺寸值