Android 中自定義控件和屬性(attr.xml,declare-styleable,TypedArray)的方法和使用

本文轉載自http://blog.csdn.net/jincf2011/article/details/6344678java

今天咱們的教程是根據前面一節擴展進行的,若是你沒有看,請點擊 Android高手進階教程(三) 查看第三課,這樣跟容易方便你的理解!android

xml 文件裏定義控件的屬性,咱們已經習慣了android:attrs="" ,那麼咱們能不能定義本身的屬性能,好比:test:attrs="" 呢?答案是確定的.編程

進入主題。大體如下步驟:canvas

1、 在res/values 文件下定義一個attrs.xml 文件.代碼以下:app

  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>  

2、 咱們在MyView.java 代碼編寫以下,其中下面的構造方法是重點,咱們獲取定義的屬性R.sytleable.MyView_textColor, 獲取方法中後面一般設定默認值(float textSize = a.getDimension(R.styleable.MyView_textSize, 36 ); ) 防止咱們在xml 文件中沒有定義.從而使用默認值!ide

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. }  

3、將咱們自定義的MyView 加入佈局main.xml 文件中,而且使用自定義屬性,自定義屬性必須加上:性能

    " xmlns:test ="http://schemas.android.com/apk/res/com.android.tutor"  ,test是自定義屬性的前綴,           com.android.tutor 是咱們包名.this

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>  

4、運行之效果以下圖:

參考文章二:

 

Android 自定義View 己經不是什麼新鮮話題,Android Api提供了一大堆基礎組件給咱們,須要什麼特定功能還須要咱們繼承它們而後定製更加豐富的功能。前面有篇文章也說過爲自定義VIEW添加屬性,但只是一筆帶過,這裏就拿這點來講說吧。

第一種添加屬性的方法,以前我也是常用這種寫法,代碼以下:

複製代碼
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麻煩共享),第二種寫法,能夠即支持引用資源又能夠直接輸入作操做,爲編程帶來更多的方便性。

種種都說明,第二種寫法更具規範性,功能更性,代碼編寫 也更優雅,但我的有我的的使用習慣,我兩種都喜歡用,具體看需求吧。呵呵。。。

相關文章
相關標籤/搜索