Android系統雖然自帶瞭很多的組件,但肯定滿足我們個性化的需求,所以我們為瞭開發方便,需要自定義Android的UI組件,以實現我們個性化的需求。
自定義組合控件的步驟:
1 、自定一個View,需要繼承相對佈局,線性佈局等ViewGroup的子類。ViewGroup是一個其他控件的容器,能夠乘放各種組件。
2 、實現父類的3個構造方法。一般需要在構造方法裡始化初自定義佈局文件。
一個參數構造方法:為new控件使用
兩個參數的造方法:在調用佈局文件使用
三個參數的造方法:傳遞帶有樣式的佈局文件使用
3 、根據需求,定義一些API方法。
4 、根據需要自定義控件的屬性。可以參考TextView的屬性寫。
5 、自定義命名空間。
xmlns:xxx=”https://schemas.android.com/apk/res/” xxx為為scheam名
6 、自定義我們的屬性, 在res/values/attrs.xml(創建屬性文件)定義屬性
類似:
<
7 、使用自定義的屬性。
例如:
andy:desc_off=”設置自動更新已經關閉”
andy:desc_on=”設置自動更新已經開啟”
andy:titles=”設置自動更新”
8 、在我們自定義控件的帶兩個參數的構造方法裡面,AttributeSet attrs取出自定屬性值,關聯到自定義佈局文件對應的控件。
代碼實例如下:
1 定義一個自定義控件:setting_item_view.xml佈局文件
2 在對應的Activity佈局文件中調用
3 自定義屬性:res/values/attrs.xml
4 實現自定義組件,繼承ViewGroup的子類,實現構造方法,和對應的API方法
package com.andy.mobilesafe.ui; import com.andy.mobilesafe.R; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.CheckBox; import android.widget.RelativeLayout; import android.widget.TextView; /** * @author Zhang,Tianyou * @version 2014年11月15日 下午10:22:50 * * 自定義組合控件 兩個TextView 一個checkbox 一個View */ public class SettingItemView extends RelativeLayout { private CheckBox cb_status; private TextView tv_title; private TextView tv_desc; private String desc_on; private String desc_off; /** * 初始化佈局文件 * * @param context */ private void initView(Context context) { // 第二個為佈局文件 root第三個參數為佈局文件父類 // 把一個佈局文件 View 並加載在SettingItemView View.inflate(context, R.layout.setting_item_view, this); // View 已經加載該SettingItemView cb_status = (CheckBox) this.findViewById(R.id.cb_status); tv_desc = (TextView) this.findViewById(R.id.tv_desc); tv_title = (TextView) this.findViewById(R.id.title); } public SettingItemView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // 這個是可以傳遞一個樣式 調用 initView(context); } /** * 帶有兩個參數的構造方法 ,佈局文件使用的時間調用 * * @param context * @param attrs * 得到屬性值 */ public SettingItemView(Context context, AttributeSet attrs) { super(context, attrs); // 自定義佈局使用調用的構造方法 attrs為配置的屬性 佈局文件中使用 initView(context); String titles = attrs.getAttributeValue( "https://schemas.android.com/apk/res/com.andy.mobilesafe", "titles"); desc_off = attrs.getAttributeValue( "https://schemas.android.com/apk/res/com.andy.mobilesafe", "desc_off"); desc_on = attrs.getAttributeValue( "https://schemas.android.com/apk/res/com.andy.mobilesafe", "desc_on"); tv_title.setText(titles); setDesc(desc_off); } public SettingItemView(Context context) { super(context); // new 出的時間使用 initView(context); } /** * 校驗組合控件是否有選中 * * @return */ public boolean isChecked() { return cb_status.isChecked(); } /** * 設置組合控件選中 * * @param checked */ public void setChecked(boolean checked) { if(checked){ setDesc(desc_on); }else { setDesc(desc_off); } cb_status.setChecked(checked); } /** * 設置組合控件的描述信息 * * @param text */ public void setDesc(String text) { tv_desc.setText(text); } }