歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android自定義屬性時TypedArray的使用方法

Android自定義屬性時TypedArray的使用方法

日期:2017/3/1 9:58:37   编辑:Linux編程

有時候Android傳統的頁面布局不足以滿足我們的需求,常常需要自己定義view,通常繼承View,然後重寫構造方法以及onDraw等函數,再具體實現自己定義的復雜view。我們知道在給控件賦屬性時,通常使用的是android系統自帶的屬性,比如 android:layout_height="wrap_content",除此之外,我們亦可以自己定義屬性,這樣在使用的時候我們就可以使用形如 myapp:myTextSize="20sp"的方式了,步驟大致如下:

1》在項目文件res/value下面創建一個attr.xml文件,該文件中包含若干個attr集合,例如:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="myTextSize" format="dimension"/>
<attr name="myColor" format="color"/>
</declare-styleable>
</resources>

其中resource是跟標簽,可以在裡面定義若干個declare-styleable,<declare-styleable name="MyView">中name定義了變量的名稱,下面可以再自定義多個屬性,針對<attr name="myTextSize" format="dimension"/>來說,其屬性的名稱為"myTextSize",format指定了該屬性類型為dimension,只能表示字體的大小。

format還可以指定其他的類型比如;

reference 表示引用,參考某一資源ID
string 表示字符串
color 表示顏色值
dimension 表示尺寸值
boolean 表示布爾值
integer 表示整型值
float 表示浮點值
fraction 表示百分數
enum 表示枚舉值
flag 表示位運算

2》在使用到該自定義view的布局文件中鍵入如下的一行:

xmlns:myapp=http://schemas.android.com/apk/res/com.eyu.attrtextdemo綠色是自己定義屬性的前綴名字,粉色是項目的包名,這樣一來,在我們自己定義的view的屬性中,就可以使用自己在attr中定義的屬性啦,例如:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.eyu.attrtextdemo"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<com.eyu.attrtextdemo.MyView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
myapp:myTextSize="20sp"
myapp:myColor="#324243"/>

</LinearLayout>

Copyright © Linux教程網 All Rights Reserved