Android自定义属性简单使用说明
原创文章,转载请注明出处:http://www.cnblogs.com/baipengzhan/p/Android_attrs.html
本文从实用角度说明Android自定义属性的基本使用流程,清晰明了,希望各位阅读后能够掌握Android自定义属性的一般用法,以便以后深入的研究。
首先,我们要树立一个观点,每一个自定义属性都和一个自定义控件对应,这两个是相关的。就像Android系统中提供的各个原生控件,它们都有自己对应的属性,这个由是Android实现的,控件只能使用自己的属性,不能使用别的控件对应的属性。因此,我们不能孤立的讲解自定义属性,需要结合对应的自定义控件(不清楚自定义控件的朋友只需要稍微查看一下自定义控件的概念即可)。每个自定义控件对应的属性是一个属性集,属性集的名字就是自定义控件的简短名字,属性和控件间的联系就是通过这个名字来实现的,接下来我们具体看下步骤:
自定义属性的学习步骤共有以下4步:步骤一:创建自定义控件;步骤二:创建attrs.xml文件;步骤三:设置自定义属性集内容;步骤四:使用自定义属性。
步骤一:创建自定义控件
首先我们创建一个测试用的自定义控件,就是最简单的那种:
public class MyView extends View { public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); } public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } }
这个自定义控件叫做MyView。那我们要怎么定义这个自定义控件专属的属性集呢?看下面的步骤。
步骤二:创建attrs.xml文件
我们在res/values目录下,创建名为attrs.xml的文件。之后我们就要具体设置属性集的内容了。
步骤三:设置自定义属性集内容
我们首先看以下示例代码:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyView"> <attr name="CircleRadius" format="float" /> <attr name="type" format="boolean"/> </declare-styleable> </resources>
-
reference:引用资源
-
string:字符串
-
Color:颜色
-
boolean:布尔值
-
dimension:尺寸值
-
float:浮点型
-
integer:整型
-
fraction:百分数
-
enum:枚举类型
-
flag:位或运算
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:hehe="http://schemas.android.com/apk/res-auto"//此处设置命名空间 android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.chironmy.qqui.MyView android:layout_width="wrap_content" android:layout_height="wrap_content" hehe:type="true" hehe:CircleRadius="1.0" android:text="Hello World!" /> </RelativeLayout>