有時候android傳統的頁面佈局不足以滿足我們的需求,常常需要自己定義view,通常繼承View,然後重寫構造方法以及onDraw等函數,再具體實現自己定義的複雜view。我們知道在給控件賦屬性時,通常使用的是android系統自帶的屬性,比如
android:layout_height="wrap_content",除此之外,我們亦可以自己定義屬性,這樣在使用的時候我們就可以使用形如 myapp:myTextSize="20sp"的方式了,步驟大致如下:
1》在項目文件res/value下面創建一個attr.xml文件,該文件中包含若干個attr集合,例如:
[html]
<?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的佈局文件中鍵入如下的一行:
綠色是自己定義屬性的前綴名字,粉色是項目的包名,這樣一來,在我們自己定義的view的屬性中,就可以使用自己在attr中定義的屬性啦,例如:
[html]
<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>
3》在自定義view的代碼中引入自定義屬性,修改構造函數
context通過調用obtainStyledAttributes方法來獲取一個TypeArray,然後由該TypeArray來對屬性進行設置
obtainStyledAttributes方法有三個,我們最常用的是有一個參數的obtainStyledAttributes(int[] attrs),其參數直接styleable中獲得
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);
調用結束後務必調用recycle()方法,否則這次的設定會對下次的使用造成影響
具體如下:
[java]
package com.eyu.attrtextdemo;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View{
public Paint paint;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);
int textColor = a.getColor(R.styleable.MyView_myColor, 003344);
float textSize = a.getDimension(R.styleable.MyView_myTextSize, 33);
paint.setTextSize(textSize);
paint.setColor(textColor);
a.recycle();
}
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override www.2cto.com
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
paint.setStyle(Style.FILL);
canvas.drawText("aaaaaaa", 10, 50, paint);
}
}