android自定义属性
- 如何自定义属性
- 在res文件夹下的values目录,新建attrs.xml(如果没有此文件的话)
- 在attr.xml中定义属性,示例如下:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MapView" > <attr name="mv_background" format="reference"/> </declare-styleable> </resources>
分析一下以上代码的含义:
-
-
declare-styleable表示一个属性组,它的name必须和你的自定义控件名称一模一样;attr表示单独一个属性,name代表属性名称,format代表属性的格式,格式包括很多中:引用、枚举。。
-
-
-
- 如何使用自定义属性
- 首先加入命名空间
xmlns:app="http://schemas.android.com/apk/res-auto"
- 通过命名空间就可以使用自定义属性了
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.safeluck.flibp.view.MapView android:id="@+id/map_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" app:mv_background="@drawable/flip_board" /> </RelativeLayout>
- 首先加入命名空间
- 如何获取自定义属性
-
TypedArray typedArray = context.obtainStyledAttributes(R.styleable.MapView);
BitmapDrawable drawable = (BitmapDrawable) typedArray.getDrawable(R.styleable.MapView_mv_background);
typedArray.recycle();
-
- 需要注意的问题
-
给某个自定义属性赋值时,赋值的类型必须和format中定义的类型相似。
找到一篇不错的blog:http://www.jianshu.com/p/2c566331a71d -
attr定义的enum和flag的value必须是数字。否则无法编译通过
-
Dana.Lee
To:Dana_Lee1016@126.com