android 自定義屬性

2021-10-07 01:26:21 字數 2480 閱讀 1410

自定義之前我們首先了解一下,view的建構函式,因為自定義屬性往往在子類中獲取並使用。

/**

* code中建立view時使用的構造方法

* ****** constructor to use when creating a view from code.

*/view

(context context)

/** * 繪製xml中view時使用的構造方法

* constructor that is called when inflating a view from xml.

*/view

(context context,attributeset attrs)

/** */

view

(context context, attributeset attrs,

int defstyleattr)

/** */

view

(context context, attributeset attrs,

int defstyleattr,

int defstyleres)

在派生的時候往往需要重寫第二個建構函式,記住訪問屬性:public

實現自定義屬性步驟:

1.在values/attrs.xml中增加新增屬性(如果沒有則新建attrs.xml,new->xml->values xml file)

2.在xml中應用自定義的屬性(自定義屬性任何類都可以使用)

3.獲取並使用屬性。

新增屬性:dog_name,dog_weight

<

?xml version=

"1.0" encoding=

"utf-8"

?>

//自定義屬性命名空間:name=dog,包含屬性:name,weight

"dog"

>

"name" format=

"string"

/>

"weight" format=

"integer"

/>

<

/declare-styleable>

<

/resources>

xml中使用自定義屬性:name,weight
<

?xml version=

"1.0" encoding=

"utf-8"

?>

""""

//xmlns:dog=""

xmlns:tools=

""android:layout_width=

"match_parent"

android:layout_height=

"match_parent"

android:orientation=

"vertical"

android:fitssystemwindows=

"true"

>

android:layout_width=

"match_parent"

android:layout_height=

"10dp"

"hellow"

"10"

/>

<

/linearlayout>

view獲取並使用屬性

public

class

do**iew extends textview

}

使用系統屬性作為自定義屬性

eg:android:text,因為是系統屬性,所以不需要指定format型別。

"android:text"

/>

xml 直接使用系統定義屬性,進行賦值:

android:text=

"mydog"

android:layout_width=

"match_parent"

android:layout_height=

"10dp"

dog:name=

"hellow"

dog:weight=

"10"

/>

獲取並使用

string text = ta.

getstring

(r.styleable.dog_android_text)

;

參考部落格:

Android 自定義屬性

1 在values資料夾下新建xml檔案,命名為attrs.xml,在該檔案中新增你的自定義屬性,例如 2 在布局檔案中使用 首先要定義命名空間xmlns test 命名根據喜好可以隨便取,url中packagename為你專案的包名 具體使用 3 在自定義控制項中讀取 在使用了自定義的屬性後,會呼...

Android 自定義屬性

今天看看如何自定義屬性,先總結一下步驟 1.自定義乙個view 2.在values資料夾下新建attr.xml檔案,在裡面定義自己的屬性 3.在布局檔案中使用自定義的屬性,注意命名空間 4.在構造方法中獲取自定義的屬性 下面我們一步步來講解上面的步驟 1.寫出自己的類 public class cu...

android自定義屬性

建立自定義類myview android layout width wrap content android layout height wrap content sdj name abc sdj age 10 sdj color drawable bg shap 此時會報錯,因為缺少了sdj這個命...