自定義View之構(gòu)造函數(shù)
public DemoView(Context context) {
this(context,null);
System.out.println("=========一個(gè)參數(shù)============");
}
public DemoView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,R.style.);
System.out.println("=========兩個(gè)參數(shù)============");
}
public DemoView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
System.out.println("=========三個(gè)參數(shù)============");
}
public DemoView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
System.out.println("=========四個(gè)參數(shù)============");
}
調(diào)用說明:
(1)利用代碼直接new 布局時(shí)會(huì)調(diào)用一個(gè)參數(shù)的構(gòu)造函數(shù)严嗜。
(2)如果直接寫在xml文件中會(huì)調(diào)用二個(gè)參數(shù)的構(gòu)造函數(shù)被調(diào)用粱檀。
(3)上面的寫法永遠(yuǎn)不會(huì)調(diào)用第三個(gè),第四個(gè)構(gòu)造函數(shù)漫玄,三個(gè)茄蚯,四個(gè)參數(shù)的構(gòu)造函數(shù)通常由我們自己主動(dòng)調(diào)用。
構(gòu)造函數(shù)參數(shù)說明:
Context - 上下文睦优;
AttributeSet - xml文件中的屬性渗常;
int defStyleAttr - Theme中的默認(rèn)樣式;
int defStyleResource - defStyleAttr未使用(為0刨秆,或者未匹配到)凳谦,則應(yīng)用于View的默認(rèn)樣式忆畅;
R.style中系統(tǒng)為view定義了很多默認(rèn)主題Theme,主題中有對(duì)某些屬性的默認(rèn)賦值衡未。
說明:
一個(gè)參數(shù)的構(gòu)造函數(shù):View或者ViewGroup可以利用代碼直接new對(duì)象尸执,這時(shí)就會(huì)調(diào)用一個(gè)參數(shù)的構(gòu)造函數(shù),生成對(duì)象之后利用內(nèi)部提供的屬性設(shè)置方法就行屬性設(shè)置缓醋。
兩個(gè)參數(shù)的構(gòu)造函數(shù):用于加載xml布局文件時(shí)調(diào)用如失,通常自定義控件的自定義屬性的讀取需要用到這個(gè)構(gòu)造函數(shù)(系統(tǒng)的View,ViewGroup只要寫在xml中也會(huì)調(diào)用這個(gè)構(gòu)造函數(shù))送粱。
三個(gè)參數(shù)的構(gòu)造函數(shù):一般系統(tǒng)不會(huì)主動(dòng)調(diào)用褪贵,需要手動(dòng)調(diào)用,可以手動(dòng)傳入defStyleAttr并調(diào)用抗俄,即時(shí)在view中定義了them脆丁,style,也不會(huì)調(diào)用三參構(gòu)造函數(shù)动雹。
四個(gè)參數(shù)的構(gòu)造函數(shù)槽卫,如果第三個(gè)參數(shù)為0或者沒有定義defStyleAttr時(shí),第四個(gè)參數(shù)才起作用胰蝠,它是style的引用歼培,高版本才支持,所以一般不會(huì)用到茸塞。