原創文章,轉載請注明出處: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>