不少的Android入門程序猿來講對於Android自定義View,可能都是比較恐懼的,可是這又是高手進階的必經之路,全部準備在自定義View上面花一些功夫,多寫一些文章。先總結下自定義View的步驟:html
一、自定義View的屬性java
二、在View的構造方法中得到咱們自定義的屬性android
[ 三、重寫onMesure ]canvas
四、重寫onDrawapp
我把3用[]標出了,因此說3不必定是必須的,固然了大部分狀況下仍是須要重寫的。dom
一、自定義View的屬性,首先在res/values/ 下創建一個attrs.xml , 在裏面定義咱們的屬性和聲明咱們的整個樣式。ide
[html] view plain copy佈局
![在CODE上查看代碼片](http://static.javashuo.com/static/loading.gif)
![派生到個人代碼片](http://static.javashuo.com/static/loading.gif)
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
-
- <attr name="titleText" format="string" />
- <attr name="titleTextColor" format="color" />
- <attr name="titleTextSize" format="dimension" />
-
- <declare-styleable name="CustomTitleView">
- <attr name="titleText" />
- <attr name="titleTextColor" />
- <attr name="titleTextSize" />
- </declare-styleable>
-
- </resources>
咱們定義了字體,字體顏色,字體大小3個屬性,format是值該屬性的取值類型:post
一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;不清楚的能夠google一把。字體
而後在佈局中聲明咱們的自定義View
[objc] view plain copy
![在CODE上查看代碼片](http://static.javashuo.com/static/loading.gif)
![派生到個人代碼片](http://static.javashuo.com/static/loading.gif)
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
-
- <com.example.customview01.view.CustomTitleView
- android:layout_width="200dp"
- android:layout_height="100dp"
- custom:titleText="3712"
- custom:titleTextColor="#ff0000"
- custom:titleTextSize="40sp" />
-
- </RelativeLayout>
必定要引入 xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"咱們的命名空間,後面的包路徑指的是項目的package
二、在View的構造方法中,得到咱們的自定義的樣式
[java] view plain copy
![在CODE上查看代碼片](http://static.javashuo.com/static/loading.gif)
![派生到個人代碼片](http://static.javashuo.com/static/loading.gif)
- /**
- * 文本
- */
- private String mTitleText;
- /**
- * 文本的顏色
- */
- private int mTitleTextColor;
- /**
- * 文本的大小
- */
- private int mTitleTextSize;
-
- /**
- * 繪製時控制文本繪製的範圍
- */
- private Rect mBound;
- private Paint mPaint;
-
- public CustomTitleView(Context context, AttributeSet attrs)
- {
- this(context, attrs, 0);
- }
-
- public CustomTitleView(Context context)
- {
- this(context, null);
- }
-
- /**
- * 得到我自定義的樣式屬性
- *
- * @param context
- * @param attrs
- * @param defStyle
- */
- public CustomTitleView(Context context, AttributeSet attrs, int defStyle)
- {
- super(context, attrs, defStyle);
- /**
- * 得到咱們所定義的自定義樣式屬性
- */
- TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyle, 0);
- int n = a.getIndexCount();
- for (int i = 0; i < n; i++)
- {
- int attr = a.getIndex(i);
- switch (attr)
- {
- case R.styleable.CustomTitleView_titleText:
- mTitleText = a.getString(attr);
- break;
- case R.styleable.CustomTitleView_titleTextColor:
- // 默認顏色設置爲黑色
- mTitleTextColor = a.getColor(attr, Color.BLACK);
- break;
- case R.styleable.CustomTitleView_titleTextSize:
- // 默認設置爲16sp,TypeValue也能夠把sp轉化爲px
- mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
- TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
- break;
-
- }
-
- }
- a.recycle();
-
- /**
- * 得到繪製文本的寬和高
- */
- mPaint = new Paint();
- mPaint.setTextSize(mTitleTextSize);
- // mPaint.setColor(mTitleTextColor);
- mBound = new Rect();
- mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);
-
- }
咱們重寫了3個構造方法,默認的佈局文件調用的是兩個參數的構造方法,因此記得讓全部的構造調用咱們的三個參數的構造,咱們在三個參數的構造中得到自定義屬性。
三、咱們重寫onDraw,onMesure調用系統提供的:
[java] view plain copy
![在CODE上查看代碼片](http://static.javashuo.com/static/loading.gif)
![派生到個人代碼片](http://static.javashuo.com/static/loading.gif)
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
- {
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
- }
-
- @Override
- protected void onDraw(Canvas canvas)
- {
- mPaint.setColor(Color.YELLOW);
- canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);
-
- mPaint.setColor(mTitleTextColor);
- canvas.drawText(mTitleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint);
- }
此時的效果是:
![](http://static.javashuo.com/static/loading.gif)
是否是以爲還不錯,基本已經實現了自定義View。可是此時若是咱們把佈局文件的寬和高寫成wrap_content,會發現效果並非咱們的預期:
![](http://static.javashuo.com/static/loading.gif)
系統幫咱們測量的高度和寬度都是MATCH_PARNET,當咱們設置明確的寬度和高度時,系統幫咱們測量的結果就是咱們設置的結果,當咱們設置爲WRAP_CONTENT,或者MATCH_PARENT系統幫咱們測量的結果就是MATCH_PARENT的長度。
因此,當設置了WRAP_CONTENT時,咱們須要本身進行測量,即重寫onMesure方法」:
重寫以前先了解MeasureSpec的specMode,一共三種類型:
EXACTLY:通常是設置了明確的值或者是MATCH_PARENT
AT_MOST:表示子佈局限制在一個最大值內,通常爲WARP_CONTENT
UNSPECIFIED:表示子佈局想要多大就多大,不多使用
下面是咱們重寫onMeasure代碼:
[java] view plain copy
![在CODE上查看代碼片](http://static.javashuo.com/static/loading.gif)
![派生到個人代碼片](http://static.javashuo.com/static/loading.gif)
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
- {
- int widthMode = MeasureSpec.getMode(widthMeasureSpec);
- int widthSize = MeasureSpec.getSize(widthMeasureSpec);
- int heightMode = MeasureSpec.getMode(heightMeasureSpec);
- int heightSize = MeasureSpec.getSize(heightMeasureSpec);
- int width;
- int height ;
- if (widthMode == MeasureSpec.EXACTLY)
- {
- width = widthSize;
- } else
- {
- mPaint.setTextSize(mTitleTextSize);
- mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds);
- float textWidth = mBounds.width();
- int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight());
- width = desired;
- }
-
- if (heightMode == MeasureSpec.EXACTLY)
- {
- height = heightSize;
- } else
- {
- mPaint.setTextSize(mTitleTextSize);
- mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds);
- float textHeight = mBounds.height();
- int desired = (int) (getPaddingTop() + textHeight + getPaddingBottom());
- height = desired;
- }
-
-
-
- setMeasuredDimension(width, height);
- }
如今咱們修改下佈局文件:
[html] view plain copy
![在CODE上查看代碼片](http://static.javashuo.com/static/loading.gif)
![派生到個人代碼片](http://static.javashuo.com/static/loading.gif)
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
-
- <com.example.customview01.view.CustomTitleView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- custom:titleText="3712"
- android:padding="10dp"
- custom:titleTextColor="#ff0000"
- android:layout_centerInParent="true"
- custom:titleTextSize="40sp" />
-
- </RelativeLayout>
如今的效果是:
![](http://static.javashuo.com/static/loading.gif)
徹底複合咱們的預期,如今咱們能夠對高度、寬度進行隨便的設置了,基本能夠知足咱們的需求。
固然了,這樣下來咱們這個自定義View與TextView相比豈不是沒什麼優點,全部咱們以爲給自定義View添加一個事件:
在構造中添加:
[java] view plain copy
![在CODE上查看代碼片](http://static.javashuo.com/static/loading.gif)
![派生到個人代碼片](http://static.javashuo.com/static/loading.gif)
- this.setOnClickListener(new OnClickListener()
- {
-
- @Override
- public void onClick(View v)
- {
- mTitleText = randomText();
- postInvalidate();
- }
-
- });
[java] view plain copy
![在CODE上查看代碼片](http://static.javashuo.com/static/loading.gif)
![派生到個人代碼片](http://static.javashuo.com/static/loading.gif)
- private String randomText()
- {
- Random random = new Random();
- Set<Integer> set = new HashSet<Integer>();
- while (set.size() < 4)
- {
- int randomInt = random.nextInt(10);
- set.add(randomInt);
- }
- StringBuffer sb = new StringBuffer();
- for (Integer i : set)
- {
- sb.append("" + i);
- }
-
- return sb.toString();
- }
下面再來運行:
![](http://static.javashuo.com/static/loading.gif)
咱們添加了一個點擊事件,每次讓它隨機生成一個4位的隨機數,有興趣的能夠在onDraw中添加一點噪點,而後改寫爲驗證碼,是否是感受很不錯。