在xml 文件裡定義控件的屬性,我們已經習慣瞭android:attrs="" ,那麼我們能不能定義自己的屬性能,比如:test:attrs="" 呢?答案是肯定的.
進入主題。大致以下步驟:
一、 在res/values 文件下定義一個attrs.xml 文件.代碼如下:
1. <?xml version="1.0" encoding="utf-8"?>
2. <resources>
3. <declare-styleable name="MyView">
4. <attr name="textColor" format="color" />
5. <attr name="textSize" format="dimension" />
6. </declare-styleable>
7. </resources>
二、 我們在MyView.java 代碼編寫如下,其中下面的構造方法是重點,我們獲取定義的屬性R.sytleable.MyView_textColor, 獲取方法中後面通常設定默認值(float textSize = a.getDimension(R.styleable.MyView_textSize, 36 ); ), 防止我們在xml 文件中沒有定義.從而使用默認值!
MyView 就是定義在<declare-styleable name="MyView "></declare-styleable> 裡的 名字,獲取裡面屬性用 名字_ 屬性 連接起來就可以.TypedArray 通常最後調用 .recycle() 方法,為瞭保持以後使用該屬性一致性!
1. public MyView(Context context,AttributeSet attrs)
2. {
3. super(context,attrs);
4. mPaint = new Paint();
5.
6. TypedArray a = context.obtainStyledAttributes(attrs,
7. R.styleable.MyView);
8.
9. int textColor = a.getColor(R.styleable.MyView_textColor,
10. 0XFFFFFFFF);
11. float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
12.
13. mPaint.setTextSize(textSize);
14. mPaint.setColor(textColor);
15.
16. a.recycle();
17. }
MyView.java MyView控件全部代碼如下:
1. package com.android.tutor;
2. import android.content.Context;
3. import android.content.res.TypedArray;
4. import android.graphics.Canvas;
5. import android.graphics.Color;
6. import android.graphics.Paint;
7. import android.graphics.Rect;
8. import android.graphics.Paint.Style;
9. import android.util.AttributeSet;
10. import android.view.View;
11. public class MyView extends View {
12. private Paint mPaint;
13. private Context mContext;
14. private static final String mString = "Welcome to Mr Wei's blog";
15.
16. public MyView(Context context) {
17. super(context);
18. mPaint = new Paint();
19. }
20. public MyView(Context context,AttributeSet attrs)
21. {
22. super(context,attrs);
23. mPaint = new Paint();
24.
25. TypedArray a = context.obtainStyledAttributes(attrs,
26. R.styleable.MyView);
27.
28. int textColor = a.getColor(R.styleable.MyView_textColor,
29. 0XFFFFFFFF);
30. float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
31.
32. mPaint.setTextSize(textSize);
33. mPaint.setColor(textColor);
34.
35. a.recycle();
36. }
37. @Override
38. protected void onDraw(Canvas canvas) {
39. // TODO Auto-generated method stub
40. super.onDraw(canvas);
41. //設置填充
42. mPaint.setStyle(Style.FILL);
43.
44. //畫一個矩形,前倆個是矩形左上角坐標,後面倆個是右下角坐標
45. canvas.drawRect(new Rect(10, 10, 100, 100), mPaint);
46.
47. mPaint.setColor(Color.BLUE);
48. //繪制文字
49. canvas.drawText(mString, 10, 110, mPaint);
50. }
51. }
三、將我們自定義的MyView 加入佈局main.xml 文件中,並且使用自定義屬性,自定義屬性必須加上:
" xmlns:test ="http://schemas.android.com/apk/res/com.android.tutor" ,test是自定義屬性的前綴, com.android.tutor 是我們包名.
main.xml 全部代碼如下:
1. <?xml
2. version="1.0" encoding="utf-8"?>
3. <LinearLayout
4. xmlns:android="http://schemas.android.com/apk/res/android"
5.
6. xmlns:test="http://schemas.android.com/apk/res/com.android.tutor"
7. android:orientation="vertical"
8. android:layout_width="fill_parent"
9. android:layout_height="fill_parent"
10. >
11. <TextView
12. android:layout_width="fill_parent"
13. android:layout_height="wrap_content"
14. android:text="@string/hello"
15. />
16. <com.android.tutor.MyView
17. android:layout_width="fill_parent"
18. android:layout_height="fill_parent"
19. test:textSize="20px"
20. test:textColor="#fff"
21. />
22. </LinearLayout>
四、運行之效果如下圖:
參考文章二:
Android 自定義View 己經不是什麼新鮮話題,Android Api提供瞭一大堆基礎組件給我們,需要什麼特定功能還需要我們繼承它們然後定制更加豐富的功能。前面有篇文章也說過為自定義VIEW添加屬性,但隻是一筆帶過,這裡就拿這點來說說吧。
第一種添加屬性的方法,之前我也是經常使用這種寫法,代碼如下:www.aiwalls.com
package com.terry.attrs;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class EditTextExt1 extends LinearLayout {
private String Text = "" ;
public EditTextExt1(Context context) {
this (context, null );
// TODO Auto-generated constructor stub
}
public EditTextExt1(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
int resouceId = – 1 ;
TextView tv = new TextView(context);
EditText et = new EditText(context);
resouceId = attrs.getAttributeResourceValue( null , " Text " , 0 );
if (resouceId > 0 ) {
Text = context.getResources().getText(resouceId).toString();
} else {
Text = "" ;
}
tv.setText(Text);
addView(tv);
addView(et, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
this .setGravity(LinearLayout.VERTICAL);
}
}
這種寫法,簡單明瞭,不需要額外XML的配置,就可以在我們的VIEW文件下使用。
以上代碼通過構造函數中引入的AttributeSet 去查找XML佈局的屬性名稱,然後找到它對應引用的資源ID去找值。使用也時分方便。所以一直以來我也是很喜歡這種寫法。
如上,自定好VIEW文件就可以在XML佈局下如此使用:
< com.terry.attrs.EditTextExt1 android:id = " @+id/ss3 "
android:layout_width = " wrap_content " android:layout_height = " wrap_content "
Text = " @string/app_name " ></ com.terry.attrs.EditTextExt1 >
好瞭,這是第一種為VIEW註冊屬性的寫法,比較簡單就不多介紹。
下面是第二為VIEW註冊屬性的寫法,這裡也要重點說說第二種註冊 屬性的寫法和使用要點,先看一下JAVA代碼要如何編寫:
package com.terry.attrs;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class EditTextExt extends LinearLayout {
public EditTextExt(Context context) {
this (context, null );
// TODO Auto-generated constructor stub
}
public EditTextExt(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
int resouceId = – 1 ;
TypedArray typeArray = context.obtainStyledAttributes(attrs,
R.styleable.EditTextExt);
TextView tv = new TextView(context);
EditText et = new EditText(context);
int N = typeArray.getIndexCount();
for ( int i = 0 ; i < N; i ++ ) {
int attr = typeArray.getIndex(i);
switch (attr) {
case R.styleable.EditTextExt_Oriental:
resouceId = typeArray.getInt(R.styleable.EditTextExt_Oriental,
0 );
this .setOrientation(resouceId == 1 ? LinearLayout.HORIZONTAL
: LinearLayout.VERTICAL);
break ;
case R.styleable.EditTextExt_Text:
resouceId = typeArray.getResourceId(
R.styleable.EditTextExt_Text, 0 );
tv.setText(resouceId > 0 ? typeArray.getResources().getText(
resouceId) : typeArray
.getString(R.styleable.EditTextExt_Text));
break ;
}
}
addView(tv);
addView(et);
typeArray.recycle();
}
}
如上代碼,跟前面代碼一樣。還是用的一個EDITTEXT和TEXTVIEW做基礎組件。下面我們一步步分析上面的代碼:
R.styleable.EditTextExt 代碼的是一個attrs指向的一個declare-styleable 的標簽,如下代碼:
<? xml version="1.0" encoding="UTF-8" ?>
< resources >
< declare-styleable name ="EditTextExt" >
< attr name ="Text" format ="reference|string" ></ attr >
< attr name ="Oriental" >
< enum name ="Horizontal" value ="1" ></ enum >
< enum name ="Vertical" value ="0" ></ enum >
</ attr >
</ declare-styleable >
</ resources >
這個文件位於,values下的attrs.xml目錄下面,我比較喜歡一個自定義View 對應一個declare-styleable標簽。
Tip:一個自定義View 第一部分的代碼,
TypedArray typeArray = context.obtainStyledAttributes(attrs,
R.styleable.EditTextExt);
指定為一個declare-styleable,而在declare-styleable 下的attr (即各屬性)Android 的ADT 將會自動生成為declare-styleable的name 名字加上“_”加上對應attr(即屬性名稱)的名稱,如上(EditTextExt_Text)我們要得到Text 就需要R.styleable.EditTextExt_Text,這一點的話可以看看R.java生成文件:
public static final class styleable {
/** Attributes that can be used with a EditTextExt.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{ @link #EditTextExt_Oriental com.terry.attrs:Oriental}</code></td><td></td></tr>
<tr><td><code>{ @link #EditTextExt_Text com.terry.attrs:Text}</code></td><td></td></tr>
</table>
@see #EditTextExt_Oriental
@see #EditTextExt_Text
*/
public static final int [] EditTextExt = {
0x7f010000 , 0x7f010001
};
/**
<p>This symbol is the offset where the { @link com.terry.attrs.R.attr#Oriental}
attribute's value can be found in the { @link #EditTextExt} array.
<p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>Horizontal</code></td><td>1</td><td></td></tr>
<tr><td><code>Vertical</code></td><td>0</td><td></td></tr>
</table>
@attr name android:Oriental
*/
public static final int EditTextExt_Oriental = 1 ;
/**
<p>This symbol is the offset where the { @link com.terry.attrs.R.attr#Text}
attribute's value can be found in the { @link #EditTextExt} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a string value, using '//;' to escape characters such as '//n' or '//uxxxx' for a unicode character.
@attr name android:Text
*/
public static final int EditTextExt_Text = 0 ;
};
好瞭,上述的代碼寫完,我們要在XML佈局如何使用呢?這個會跟Android 提供的基礎組件的使用方法是一致的。首先,我們要為其提供一個引用包名如下:
xmlns:android = " http://schemas.android.com/apk/res/android "
xmlns:terry = " http://schemas.android.com/apk/res/com.terry.attrs "
上面提供的是android 基礎組件的包名,和我們自己組件的包名。
寫好瞭包名。就可以像使用andriod 基礎組件一樣使用瞭,如下全部XML佈局源碼:
<? xml version="1.0" encoding="utf-8" ?>
< LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android"
xmlns:terry ="http://schemas.android.com/apk/res/com.terry.attrs"
android:orientation ="vertical" android:layout_width ="fill_parent"
android:layout_height ="fill_parent" >
< TextView android:layout_width ="fill_parent"
android:layout_height ="wrap_content" android:text ="@string/hello" />
< com.terry.attrs.EditTextExt android:id ="@+id/ss"
android:layout_width ="fill_parent" android:layout_height ="wrap_content"
terry:Text ="fdsafda" terry:Oriental ="Vertical" ></ com.terry.attrs.EditTextExt >
< com.terry.attrs.EditTextExt1 android:id ="@+id/ss3"
android:layout_width ="wrap_content" android:layout_height ="wrap_content"
Text ="@string/app_name" ></ com.terry.attrs.EditTextExt1 >
</ LinearLayout >
運行效果如下:
這是這兩種為Android 註冊 屬性的使用方法,那麼兩者有什麼區別呢?
在這裡我認為起碼有五點,大傢可以找找看還有什麼區別:
• 第二種可以編譯時報錯,如果編程人員隨便輸入什麼第一種是不會報錯的,第二種可以支持代碼檢測功能。
• 第二種寫法,跟Android 屬性標準寫法是一致的,而且可以統一書法規則。
• 第二種寫法,可以支持數據格式的驗證,比如我們在attrs上註明隻支持integer 那麼就不可以使用字符串,這是第一種達不到的。
• 第二種寫法,可以為VIEW提供選擇操作,比如如上我們使用的ENUM讓VIEW對應的屬性支持ENUM列表,或者為其提供BOOL等隻有雙項選擇的操作。
• 第一種寫法,所有的屬性必須是引用自資源(不大確定,如果朋友有什麼好的DEMO麻煩共享),第二種寫法,可以即支持引用資源又可以直接輸入做操作,為編程帶來更多的方便性。
種種都說明,第二種寫法更具規范性,功能更性,代碼編寫 也更優雅,但個人有個人的使用習慣,我兩種都喜歡用,具體看需求吧。呵呵。。。