步驟1:建立自定義控件類,如繼承View的類,並複寫
public MyView(Context context, AttributeSet attrs){}構造方法
步驟2:在values目錄下建立attrs.xml文件,內容格式如下:
步驟3:在佈局中建立自定義控件,控件名稱爲該自定義視圖類的類名(包括包名)
步驟4:在佈局文件開始部分聲明命名空間,格式見下方實例
步驟5:步驟1中的構造方法中通過
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyToggleBtn);
獲得自定義的屬性,再根據迭代後
for (int i = 0; i < ta.getIndexCount(); i++) {}
獲取相對應的自定義屬性的值。
以下是一個實例
//step1 attrs.xml文件內容
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 聲名屬性集的名稱 -->
<declare-styleable name="MyToggleBtn">
<!-- 聲名一個屬性 name是my_background 類型爲 引用類型 引用資源ID -->
<attr name="my_background" format="reference" />
<!-- 聲名一個屬性 name是my_slide_btn 類型爲 引用類型 引用資源ID -->
<attr name="my_slide_btn" format="reference" />
<!-- 聲名一個屬性 name是curr_state 類型爲 boolean 類型-->
<attr name="curr_state" format="boolean" />
</declare-styleable>
</resources>
//step2 佈局文件中建立控件並定義自定義屬性
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:gymyung="http://schemas.android.com/apk/res/com.g36bk.viewtest"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.g36bk.viewtest.View.ToggleView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
gymyung:curr_state="true"
gymyung:my_background="@drawable/switch_background"
gymyung:my_slide_btn="@drawable/slide_button"
/>
</RelativeLayout>
/**
參數解釋:
聲明命名空間:xmlns:gymyung="http://schemas.android.com/apk/res/com.g36bk.viewtest"
格式:xmlns(xml name space):gymyung(前綴)="http://schemas.android.com/apk/res/(固定寫法)com.g36bk.viewtest(程序包名)"
定義自定義控件:<com.g36bk.viewtest.View.ToggleView />
定義自定義屬性:gymyung:curr_state="true"
gymyung:my_background="@drawable/switch_background"
gymyung:my_slide_btn="@drawable/slide_button"
*/
//step3 控件應用類中找到屬性的值
/**
參數解釋:
聲明命名空間:xmlns:gymyung="http://schemas.android.com/apk/res/com.g36bk.viewtest"
格式:xmlns(xml name space):gymyung(前綴)="http://schemas.android.com/apk/res/(固定寫法)com.g36bk.viewtest(程序包名)"
定義自定義控件:<com.g36bk.viewtest.View.ToggleView />
定義自定義屬性:gymyung:curr_state="true"
gymyung:my_background="@drawable/switch_background"
gymyung:my_slide_btn="@drawable/slide_button"
*/
//step3 控件應用類中找到屬性的值
/*********************************
附:在控件中若聲明沒有命名空間的屬性時,系統並不會出現報錯信息
但在視圖中通過同樣的方式可獲取該屬性的值
但對於字符串或布爾類型類似的屬性可正常獲取,
而類似引入連接比如圖片資源的引用,獲取到的值是所配置的字符串信息,
系統並沒有進行相應的轉換
**********************************/