Android自定義屬性

2021-08-10 02:03:14 字數 1672 閱讀 7357

一、前言

對於自定義屬性,我想新手一定是雲裡霧裡吧,看了幾遍部落格,感覺寫的有點複雜,我就根據自己的使用簡單的寫個用法和步驟吧。

二、步驟

1、 自定義乙個customview(extends view )類,這個就不需要講了吧,直接新建乙個就行

2、編寫values/attrs.xml,在其中編寫styleable和item等標籤元素

name=

"customattributeview"

>

name=

"my_name"

format=

"string"

/>

name=

"my_age"

format=

"integer"

/>

name=

"my_bg"

format=

"reference|color"

/>

format 常用型別

3、在布局檔案中customview使用自定義的屬性(注意namespace,命名空間)

<?

xml version=

"1.0"

encoding=

"utf-8"

?>

xmlns:

android

=""xmlns:

tools

=""xmlns:

=""android

:id=

"@+id/activity_main"

android

:layout_width=

"match_parent"

android

:layout_height=

"match_parent"

tools

:context=

"com.liupeng.lp.customview.mainactivity"

>

android

:layout_width=

"wrap_content"

android

:layout_height=

"wrap_content"

:my_name=

"lp"

:my_age=

"20"

:my_bg=

"@mipmap/ic_launcher"

/>

4、在customview的構造方法中通過typedarray獲取,有三種方法得到屬性值。

public class customattributeview extends view

//3.使用系統工具

typedarray typedarray = context.obtainstyledattributes(attrs, r.styleable.customattributeview);

final int n = typedarray.getindexcount();

for (int i = 0

; i < n; i++)

}array.recycle();

} @override

protected void

ondraw(canvas canvas)

demo位址

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這個命...