1. 程式人生 > >Android 自定義View (一)

Android 自定義View (一)

轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/24252901

很多的Android入門程式猿來說對於Android自定義View,可能都是比較恐懼的,但是這又是高手進階的必經之路,所有準備在自定義View上面花一些功夫,多寫一些文章。先總結下自定義View的步驟:

1、自定義View的屬性

2、在View的構造方法中獲得我們自定義的屬性

[ 3、重寫onMesure ]

4、重寫onDraw

我把3用[]標出了,所以說3不一定是必須的,當然了大部分情況下還是需要重寫的。

1、自定義View的屬性,首先在res/values/  下建立一個attrs.xml , 在裡面定義我們的屬性和宣告我們的整個樣式。

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <resources>
  3.     <attrname="titleText"format="string"/>
  4.     <attrname="titleTextColor"format="color"/>
  5.     <attrname="titleTextSize"format="dimension"/>
  6.     <declare-styleablename="CustomTitleView">
  7.         <attrname="titleText"/>
  8.         <attrname="titleTextColor"/>
  9.         <attrname="titleTextSize"/>
  10.     </declare-styleable>
  11. </resources>
我們定義了字型,字型顏色,字型大小3個屬性,format是值該屬性的取值型別:

一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;不清楚的可以google一把。

然後在佈局中宣告我們的自定義View

  1. <RelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
  2.     xmlns:tools="http://schemas.android.com/tools"
  3.     xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"
  4.     android:layout_width="match_parent"
  5.     android:layout_height="match_parent" >  
  6.     <com.example.customview01.view.CustomTitleView
  7.         android:layout_width="200dp"
  8.         android:layout_height="100dp"
  9.         custom:titleText="3712"
  10.         custom:titleTextColor="#ff0000"
  11.         custom:titleTextSize="40sp" />  
  12. </RelativeLayout>  

一定要引入 xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"我們的名稱空間,後面的包路徑指的是專案的package

2、在View的構造方法中,獲得我們的自定義的樣式

  1. /** 
  2.      * 文字 
  3.      */
  4.     private String mTitleText;  
  5.     /** 
  6.      * 文字的顏色 
  7.      */
  8.     privateint mTitleTextColor;  
  9.     /** 
  10.      * 文字的大小 
  11.      */
  12.     privateint mTitleTextSize;  
  13.     /** 
  14.      * 繪製時控制文字繪製的範圍 
  15.      */
  16.     private Rect mBound;  
  17.     private Paint mPaint;  
  18.     public CustomTitleView(Context context, AttributeSet attrs)  
  19.     {  
  20.         this(context, attrs, 0);  
  21.     }  
  22.     public CustomTitleView(Context context)  
  23.     {  
  24.         this(context, null);  
  25.     }  
  26.     /** 
  27.      * 獲得我自定義的樣式屬性 
  28.      *  
  29.      * @param context 
  30.      * @param attrs 
  31.      * @param defStyle 
  32.      */
  33.     public CustomTitleView(Context context, AttributeSet attrs, int defStyle)  
  34.     {  
  35.         super(context, attrs, defStyle);  
  36.         /** 
  37.          * 獲得我們所定義的自定義樣式屬性 
  38.          */
  39.         TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyle, 0);  
  40.         int n = a.getIndexCount();  
  41.         for (int i = 0; i < n; i++)  
  42.         {  
  43.             int attr = a.getIndex(i);  
  44.             switch (attr)  
  45.             {  
  46.             case R.styleable.CustomTitleView_titleText:  
  47.                 mTitleText = a.getString(attr);  
  48.                 break;  
  49.             case R.styleable.CustomTitleView_titleTextColor:  
  50.                 // 預設顏色設定為黑色
  51.                 mTitleTextColor = a.getColor(attr, Color.BLACK);  
  52.                 break;  
  53.             case R.styleable.CustomTitleView_titleTextSize:  
  54.                 // 預設設定為16sp,TypeValue也可以把sp轉化為px
  55.                 mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(  
  56.                         TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));  
  57.                 break;  
  58.             }  
  59.         }  
  60.         a.recycle();  
  61.         /** 
  62.          * 獲得繪製文字的寬和高 
  63.          */
  64.         mPaint = new Paint();  
  65.         mPaint.setTextSize(mTitleTextSize);  
  66.         // mPaint.setColor(mTitleTextColor);
  67.         mBound = new Rect();  
  68.         mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);  
  69.     }  

我們重寫了3個構造方法,預設的佈局檔案呼叫的是兩個引數的構造方法,所以記得讓所有的構造呼叫我們的三個引數的構造,我們在三個引數的構造中獲得自定義屬性。

3、我們重寫onDraw,onMesure呼叫系統提供的:

  1. @Override
  2.     protectedvoid onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
  3.     {  
  4.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  5.     }  
  6.     @Override
  7.     protectedvoid onDraw(Canvas canvas)  
  8.     {  
  9.         mPaint.setColor(Color.YELLOW);  
  10.         canvas.drawRect(00, getMeasuredWidth(), getMeasuredHeight(), mPaint);  
  11.         mPaint.setColor(mTitleTextColor);  
  12.         canvas.drawText(mTitleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint);  
  13.     }  
此時的效果是:

是不是覺得還不錯,基本已經實現了自定義View。但是此時如果我們把佈局檔案的寬和高寫成wrap_content,會發現效果並不是我們的預期:


系統幫我們測量的高度和寬度都是MATCH_PARNET,當我們設定明確的寬度和高度時,系統幫我們測量的結果就是我們設定的結果,當我們設定為WRAP_CONTENT,或者MATCH_PARENT系統幫我們測量的結果就是MATCH_PARENT的長度。

所以,當設定了WRAP_CONTENT時,我們需要自己進行測量,即重寫onMesure方法”:

重寫之前先了解MeasureSpec的specMode,一共三種類型:

EXACTLY:一般是設定了明確的值或者是MATCH_PARENT

AT_MOST:表示子佈局限制在一個最大值內,一般為WARP_CONTENT

UNSPECIFIED:表示子佈局想要多大就多大,很少使用

下面是我們重寫onMeasure程式碼:

  1. @Override
  2. protectedvoid onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
  3. {  
  4.     int widthMode = MeasureSpec.getMode(widthMeasureSpec);  
  5.     int widthSize = MeasureSpec.getSize(widthMeasureSpec);  
  6.     int heightMode = MeasureSpec.getMode(heightMeasureSpec);  
  7.     int heightSize = MeasureSpec.getSize(heightMeasureSpec);  
  8.     int width;  
  9.     int height ;  
  10.     if (widthMode == MeasureSpec.EXACTLY)  
  11.     {  
  12.         width = widthSize;  
  13.     } else
  14.     {  
  15.         mPaint.setTextSize(mTitleTextSize);  
  16.         mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds);  
  17.         float textWidth = mBounds.width();  
  18.         int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight());  
  19.         width = desired;  
  20.     }  
  21.     if (heightMode == MeasureSpec.EXACTLY)  
  22.     {  
  23.         height = heightSize;  
  24.     } else
  25.     {  
  26.         mPaint.setTextSize(mTitleTextSize);  
  27.         mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds);  
  28.         float textHeight = mBounds.height();  
  29.         int desired = (int) (getPaddingTop() + textHeight + getPaddingBottom());  
  30.         height = desired;  
  31.     }  
  32.     setMeasuredDimension(width, height);  
  33. }  

現在我們修改下佈局檔案:
  1. <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  2.     xmlns:tools="http://schemas.android.com/tools"
  3.     xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"
  4.     android:layout_width="match_parent"
  5.     android:layout_height="match_parent">
  6.     <com.example.customview01.view.CustomTitleView
  7.         android:layout_width="wrap_content"
  8.         android:layout_height="wrap_content"
  9.         custom:titleText="3712"
  10.         android:padding="10dp"
  11.         custom:titleTextColor="#ff0000"
  12.         android:layout_centerInParent="true"
  13.         custom:titleTextSize="40sp"/>
  14. </RelativeLayout>

現在的效果是:


完全複合我們的預期,現在我們可以對高度、寬度進行隨便的設定了,基本可以滿足我們的需求。

當然了,這樣下來我們這個自定義View與TextView相比豈不是沒什麼優勢,所有我們覺得給自定義View新增一個事件:

在構造中新增:

  1. this.setOnClickListener(new OnClickListener()  
  2.         {  
  3.             @Override
  4.             publicvoid onClick(View v)  
  5.             {  
  6.                 mTitleText = randomText();  
  7.                 postInvalidate();  
  8.             }  
  9.         });  

  1. private String randomText()  
  2.     {  
  3.         Random random = new Random();  
  4.         Set<Integer> set = new HashSet<Integer>();  
  5.         while (set.size() < 4)  
  6.         {  
  7.             int randomInt = random.nextInt(10);  
  8.             set.add(randomInt);  
  9.         }  
  10.         StringBuffer sb = new StringBuffer();  
  11.         for (Integer i : set)  
  12.         {  
  13.             sb.append("" + i);  
  14.         }  
  15.         return sb.toString();  
  16.     }  

下面再來執行:


我們添加了一個點選事件,每次讓它隨機生成一個4位的隨機數,有興趣的可以在onDraw中新增一點噪點,然後改寫為驗證碼,是不是感覺很不錯。

好了,各位學習的,打醬油的留個言,頂個唄~