自定義view的構造方法

2021-08-09 02:51:19 字數 1512 閱讀 7358

首先view有三個構造方法,如下:

第乙個構造方法很簡單,就是通過**建立時才使用。下面主要詳細介紹第二個和第三個。

它的說明也就是:當我從xml中載入view的時候,這個構造器才會被呼叫。其第二個引數中就包含自定義的屬性。

接下來講解自定義屬性:

自定義屬性用法第一步:

在value資料夾中新建乙個xml檔案,檔名可以隨意取,不過一般定義成attrs。在其中用到兩個標籤,例如:

關於這些標籤的用法可參照

自定義屬性用法第二步:

typedarray type = context.obtainstyledattributes(attrs, r.styleable.customview);獲得typearray後,從其中得到值

int color = type.getcolor(r.styleable.customview_android_textcolor,color.red); 最後

typedarray

通常最後呼叫

.recycle()

方法,為了保持以後使用該屬性一致性!

用法參照

第三個引數官方有這樣的說明:

預設的風格去應用到這個view上。如果是0,沒有風格將會被應用(除了被包含在主題中)。這個也許是乙個屬性的資源,它的值是從當前的主題中檢索,或者是乙個明確的風格資源。

1.從主題中獲取:

在attrs中定義乙個屬性customstyle" format="reference"/>,也就是這個屬性會參照乙個style。

activity中定義主題:android:theme="@style/styledindicators"  ,這個styledindicators中包含

customstyle">@style/customindicator,attrs中的屬性在customindicator中寫值

然後在**中

public customview(context context, attributeset attrs) {

// todo auto-generated constructor stub

this(context,attrs,r.attr.customstyle);

public customview(context context, attributeset attrs, int defstyleattr) {

super(context, attrs, defstyleattr);

// todo auto-generated constructor stub

typedarray type = context.obtainstyledattributes(attrs,r.styleable.customview,defstyleattr,0);

接下來就跟第二個構造方法中做的一樣了

2.從風格中獲取:

this(context,attrs,r.style.customindicator);

和typedarray type = con

Android自定義View的建構函式

自定義view是android中乙個常見的需求,每個自定義的view都需要實現三個基本的建構函式,而這三個建構函式又有兩種常見的寫法。每個建構函式分別呼叫基類的建構函式,再呼叫乙個公共的初始化方法做額外初始化。public class myview extends listview public m...

關於自定義View的四個構造方法

如果用 來例項化乙個自定義的view,會呼叫第乙個構造方法。view new view context 如果在xml中 包名 自定義view的名字 android id id imageview android layout width match parent android layout hei...

自定義View之onMeasure 方法

乙個view從建立到被繪製到螢幕上,需要完成measure 測量 layout 布置 draw 繪製 三個步驟,分別對應view中的measure layout draw 三個方法。網上關於這三個方法的原始碼解析文章有很多,而且一般情況下也不會去重寫它們 measure 方法還無法覆蓋 因此本文不打...