android 自定义属性

发表于:,更新于:,By Sally
大纲
  1. 1. 创建一个xml文件
    1. 1.1. format 的常用类型
  2. 2. 在布局文件中使用
    1. 2.1. 定义自己的命名空间
    2. 2.2. 布局文件中使用
  3. 3. 在自定义控件的方法中,获得(自定义的)属性和值

创建一个xml文件

  • 常用命名为attrs.xml,该文件默认会放在res/values/目录下
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--  声明属性集名称 -->
<declare-styleable name="MyView" >

<!--  声明属性 及其 类型 -->
<attr name="test_id" format="integer" />
<attr name="test_msg" format="string" />
<attr name="test_bitmap" format="reference" />

</declare-resources>
</resources>

format 的常用类型

  • reference 引用

  • color 颜色

  • boolean 布尔值

  • dimension 尺寸值

  • float 浮点值

  • integer 整形值

  • string 字符值

  • enum 枚举值

在布局文件中使用

  • eg:
1
2
3
4
5
6
7
8
9
<!-- xmlns : xml name space 所以,我们在使用自定义属性的时候,需要定义命名空间-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout/>

定义自己的命名空间

1
2
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:sally="http://schemas.android.com/apk/res/自己的包名"

布局文件中使用

  • 因为是一个标准的xml文件,如果自定义属性只为自己用,id="myview" text="自定义的属性" 这么写也是可以的,只是不标准,不规范罢了
1
2
3
4
5
6
7
8
9
<com.sslei.MyView
android:id="@+id/et_url"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="wrap_content"
sally:test_id="@id/myview"
sally:test_msg="自定义属性"
sally:test_bitmap="@mipmap/ic_launcher.png"
/>

在自定义控件的方法中,获得(自定义的)属性和值

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
35
36
37
38
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);

// 获得处所有的属性值
int count = attrs.getAttributeCount();
for(int i=0; i<count; i++) {
String name = attrs.getAttributeName(i);
String value = attrs.getAttributeValue(i);
System.out.println("name: " + name + " value: " + value);
}

System.out.println("+++++++++++++++++ 华丽分割线 +++++++++++++++++++++++");

/*
* 对 AttributeSet 中的原始数据,按照图纸中的(R.styleable.MyView中的类型声明)创建出来的具体对象
* 获得处自定义的,使用了的属性值
*/

TypeArray ta = context.obtainStyleAttributes(attrs, R.styleable.MyView);
int taCount = ta.getIndexCount();
for(int i=0; i<taCount; i++) {
// 控件的id值
int index = ta.getIndex(i);
System.out.println(index);

switch(index) {
case R.styleable.MyView_test_id:
int id = ta.getInt(index, -1); //获得属性值
break;
case R.styleable.MyView_test_msg:
String msg = ta.getString(index);
break;
case R.styleable.MyView_test_bitmap:
Bitmap bmp = ta.getDrawable(index);
bmp.getResourceId(index, 100);
break;
}
}
}