瞭解自定義View和繼承View,繼承ViewGroup,繼承已有View,繼承已有ViewGroup實例ji

自定義View的分類

繼承View

當咱們須要實現的效果是一個不規則效果的時候,那麼這時就須要繼承 View 來實現了,咱們須要重寫 onDraw 方法,在該方法裏實現各類不規則的圖形和效果。當咱們使用這種方式的時候,須要本身去處理 warp_content 和 padding。html

繼承ViewGroup

當系統所提供的 LinearLayout、FrameLayout 等佈局控件沒法知足咱們的需求時,這時咱們就須要使用這種方式來實現本身想要的佈局效果了。當咱們使用這種方式的時候,須要重寫 onLayout 方法來對子 View 進行佈局,以及測量自己和子 View 寬高,還須要處理自己的 padding 和子 View 的 margin。java

 

繼承已有View

當咱們須要基於已有的 View 進行擴展或修改的時候,那麼就可使用這種方式。好比說,咱們須要一個圓角的 ImageView,那麼這時就能夠繼承 ImageView 進行修改了。當咱們使用這種方式的時候,通常不須要本身去處理 wrap_content 和 padding 等,由於系統控件已經幫咱們作好了。android

繼承已有佈局

這種方式也叫作:自定義組合 View。該方式比較簡單,當咱們須要將一組 View 組合在一塊兒,方便後期複用的時候,就可使用該方法。當咱們使用這種方式的時候,不須要去處理 ViewGroup 的測量和佈局流程,由於系統控件已經幫咱們作好了。git

 

那麼下面咱們就從實例的角度來看看自定義View吧

繼承View的實例

當咱們自定義View繼承子View時,咱們須要注意的細節有:github

1 View是wrap_content時須要手動測量View的寬高canvas

2 View有padding值的時候須要處理app

 

在這裏咱們寫一個規範的自定義View, 畫出一個圓ide

注意: 要對 View 的 padding 和 LayoutParams 是 wrap_content 的狀況進行處理,不然 padding 將會沒法生效、wrap_content 的效果會和 match_parent 同樣佈局

 

其中重寫onMeasure方法, 判斷當是wrap_content的狀況時,本身測量view的寬或高this

[java] view plain copy

  1. package com.example.mycustomviewdemo;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Canvas;  
  5. import android.graphics.Color;  
  6. import android.graphics.Paint;  
  7. import android.util.AttributeSet;  
  8. import android.view.View;  
  9.   
  10. /** 
  11.  * 繼承View的自定義控件 
  12.  * 注意 view是wrap_content時須要手動測量View的寬高 
  13.  * View有padding值時須要處理 
  14.  */  
  15.   
  16. public class MyCircleView extends View {  
  17.   
  18.     private Paint mPaint;  
  19.     private int mRadius;  
  20.   
  21.     public MyCircleView(Context context) {  
  22.         this(context,null);  
  23.     }  
  24.   
  25.     public MyCircleView(Context context, AttributeSet attrs) {  
  26.         this(context, attrs,0);  
  27.     }  
  28.   
  29.     public MyCircleView(Context context, AttributeSet attrs, int defStyleAttr) {  
  30.         super(context, attrs, defStyleAttr);  
  31.         init();  
  32.     }  
  33.   
  34.     private void init() {  
  35.         mPaint = new Paint();   //初始化畫筆  
  36.         mPaint.setColor(Color.GREEN);  
  37.         mPaint.setAntiAlias(true);  
  38.   
  39.         mRadius = 80;  
  40.     }  
  41.   
  42.     @Override  
  43.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  44.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  45.   
  46.         int widthMode = MeasureSpec.getMode(widthMeasureSpec);  
  47.         int heightMode = MeasureSpec.getMode(heightMeasureSpec);  
  48.         int widthSize = MeasureSpec.getSize(widthMeasureSpec);  
  49.         int heightSize = MeasureSpec.getSize(heightMeasureSpec);  
  50.   
  51.         int width = 0;  
  52.         int height =0;  
  53.         if(widthMode == MeasureSpec.EXACTLY) {  
  54.             width = widthSize;  
  55.         }else {  
  56.             //widthMode == MeasureSpec.AT_MOST模式 本身設置控件寬度  
  57.             //當是wrap_content或者給具體dp的時候會走這裏  
  58.             width = mRadius * 2 +  getPaddingRight() + getPaddingLeft();  
  59.         }  
  60.         if(heightMode == MeasureSpec.EXACTLY) {  
  61.             height = heightSize;  
  62.         }else {  
  63.             height = mRadius * 2 + getPaddingTop() + getPaddingBottom();  
  64.         }  
  65.         //注意最後 調用這個方法 讓屬性生效  
  66.         setMeasuredDimension(width,height);  
  67.     }  
  68.   
  69.     @Override  
  70.     protected void onDraw(Canvas canvas) {  
  71.         super.onDraw(canvas);  
  72.         //處理padding  
  73.         int pl = getPaddingLeft();  
  74.         int pr = getPaddingRight();  
  75.         int pt = getPaddingTop();  
  76.         int pb = getPaddingBottom();  
  77.   
  78.         int width = getWidth() - pl - pr;  //控件自己的寬度  
  79.         int height = getHeight() - pt - pb; //控件自己的高度  
  80.   
  81.   
  82.         int centerX = width /2 + pl;  //中心點的橫座標  
  83.         int centerY = height /2  + pt;  //中心點的縱座標  
  84.   
  85.   
  86.         canvas.drawCircle(centerX,centerY,mRadius,mPaint);  
  87.     }  
  88. }  

 

繼承ViewGroup實例

當咱們自定義View繼承自ViewGroup的時候,須要實現孩子的onLayout方法指定子View的擺放位置,而且須要重寫 onMeasure 方法來測量大小。在這個實例當中,咱們簡單模仿下 LinearLayout ,只不過只實現其 Vertical 模式,在這個實例當中,咱們須要注意的細節有:

1 ViewGroup是wrap_content時須要手動測量

2 當ViewGroup自己有padding值的時候須要處理

3 當子View有margin值時須要處理

 

規範自定義ViewGroup, 這幾個細節咱們要處理,代碼:[java] view plain copy

  1. package com.example.mycustomviewdemo;  
  2.   
  3. import android.content.Context;  
  4. import android.util.AttributeSet;  
  5. import android.view.View;  
  6. import android.view.ViewGroup;  
  7.   
  8. /** 
  9.  * 繼承ViewGroup實例 
  10.  * 
  11.  * 注意: 
  12.  * ViewGroup是wrap_content須要手動測量 
  13.  * 當ViewGroup自己有padding值時要處理 
  14.  * 當子view有margin值時要處理 
  15.  */  
  16.   
  17. public class MySimpleVerticalLayout extends ViewGroup {  
  18.     private Context mContext;  
  19.   
  20.     public MySimpleVerticalLayout(Context context) {  
  21.         this(context,null);  
  22.     }  
  23.   
  24.     public MySimpleVerticalLayout(Context context, AttributeSet attrs) {  
  25.         this(context, attrs,0);  
  26.     }  
  27.   
  28.     public MySimpleVerticalLayout(Context context, AttributeSet attrs, int defStyleAttr) {  
  29.         super(context, attrs, defStyleAttr);  
  30.         mContext = context;  
  31.   
  32.     }  
  33.   
  34.     @Override  
  35.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  36.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  37.         //獲取ViewGroup測量模式  大小  
  38.         int widthMode = MeasureSpec.getMode(widthMeasureSpec);  
  39.         int heightMode = MeasureSpec.getMode(heightMeasureSpec);  
  40.         int widthSize = MeasureSpec.getSize(widthMeasureSpec);  
  41.         int heightSize = MeasureSpec.getSize(heightMeasureSpec);  
  42.   
  43.         //獲取ViewGroup的padding(內邊距)值  
  44.         int pt = getPaddingTop();  
  45.         int pb = getPaddingBottom();  
  46.         int pl = getPaddingLeft();  
  47.         int pr = getPaddingRight();  
  48.   
  49.         //先測量孩子, 才能獲得孩子具體的寬高;    ------->> 這一步很重要  
  50.         measureChildren(widthMeasureSpec,heightMeasureSpec);  
  51.   
  52.         int width = 0;  
  53.         int height = 0;  
  54.         int maxWidth = 0;  
  55.         if(widthMode == MeasureSpec.AT_MOST) {  
  56.             for(int i = 0; i < getChildCount();i++) {  
  57.                 View childAt = getChildAt(i);  
  58.                 if(childAt.getVisibility() == GONE) {  
  59.                     continue;  
  60.                 }  
  61.                 //寬度爲孩子中 最寬的一個  
  62.   
  63.   
  64.                 //孩子還有個MarginLayoutParams屬性  
  65.                 MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childAt.getLayoutParams();  
  66.                 int childWidth = childAt.getMeasuredWidth() + marginLayoutParams.leftMargin + marginLayoutParams.rightMargin;  
  67.                 maxWidth  = maxWidth > childWidth ? maxWidth : childWidth;  
  68.             }  
  69.             //將遍歷後的最寬的寬度加上左右內邊距 賦值  
  70.             width = maxWidth + pl + pr;  
  71.   
  72.         }  
  73.         if(heightMode == MeasureSpec.AT_MOST) {  
  74.             for(int i = 0; i < getChildCount();i++) {  
  75.                 View childAt = getChildAt(i);  
  76.                 if(childAt.getVisibility() == GONE) {  
  77.                     continue;  
  78.                 }  
  79.                 //高度爲全部的孩子高度之和加上內邊距之和  
  80.                 MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childAt.getLayoutParams();  
  81.                 height += childAt.getMeasuredHeight() + marginLayoutParams.topMargin + marginLayoutParams.bottomMargin;  
  82.             }  
  83.             //最終的高度  
  84.             height += (pt + pb);  
  85.         }  
  86.   
  87.         //作判斷, 並將值設置  
  88.         setMeasuredDimension(widthMode == MeasureSpec.AT_MOST ? width : widthSize,heightMode == MeasureSpec.AT_MOST ? height : heightSize);  
  89.   
  90.     }  
  91.   
  92.     /** 
  93.      * 對子View進行擺放 
  94.      * @param changed 
  95.      * @param l 
  96.      * @param t 
  97.      * @param r 
  98.      * @param b 
  99.      */  
  100.     @Override  
  101.     protected void onLayout(boolean changed, int l, int t, int r, int b) {  
  102.         //viewGroup的padding值影響孩子的擺放  
  103.         int pt = getPaddingTop();  
  104.         int pb = getPaddingBottom();  
  105.         int pl = getPaddingLeft();  
  106.         int pr = getPaddingRight();  
  107.   
  108.         int cl = 0;  
  109.         int ct = 0;  
  110.         int cr = 0;  
  111.         int cb = 0;  
  112.         int bm = 0;     //這個bm很神奇  
  113.   
  114.         for(int i =0; i < getChildCount();i++) {  
  115.             //判斷當子view沒有被Gone掉時候  
  116.             View childAt = getChildAt(i);  
  117.             if(childAt.getVisibility() != GONE) {  
  118.                 //計算每一個View的位置  
  119.                 MarginLayoutParams marginLayoutParams= (MarginLayoutParams) childAt.getLayoutParams();  
  120.                 cl = marginLayoutParams.leftMargin;  
  121.                 ct += marginLayoutParams.topMargin;  
  122.                 cr = childAt.getMeasuredWidth() + marginLayoutParams.leftMargin;  
  123.                 cb += childAt.getMeasuredHeight() + marginLayoutParams.topMargin;  
  124.                 //對子View進行佈局,  注意 必定要調用childAt.layout()方法  
  125.                 childAt.layout(cl + pl, ct + pt + bm, cr + pr,cb + pb + bm);  
  126.                 ct += childAt.getMeasuredHeight();  
  127.                 bm += marginLayoutParams.bottomMargin;  
  128.             }  
  129.         }  
  130.     }  
  131.   
  132.   
  133.   
  134.     @Override  
  135.     public LayoutParams generateLayoutParams(AttributeSet attrs) {  
  136.         return new MarginLayoutParams(mContext, attrs);  
  137.     }  
  138. }  


 

繼承已有View的實例
 

繼承自系統已有View時,通常是對其原有功能進行擴展或者修改, 好比一個Button  在這裏注意監聽器的使用

 

 

繼承已有ViewGroup的實例

這種自定義 View 的實現方式也叫作:「自定義組合控件」,是一種比較簡單的自定義 View 方式。使用這種方式時,因爲是繼承已有的系統控件,因此咱們不需去測量、佈局、處理 margin、padding等,由於系統控件自己已經處理好了。


當咱們的項目中有一些佈局在不少地方都要用到的話,那麼第一時間確定就要想到複用了。複用的話,有人可能會想到使用 include 複用佈局,可是若是這樣的話,當佈局改動性很大時,使用 include 並非很靈活。這時候,就可使用 」繼承已有 ViewGroup「 這種方式了。


下面一個實例,就拿咱們平時可能常常要寫的 Item 爲例吧:

 

[java] view plain copy

  1. package com.example.mycustomviewdemo;  
  2.   
  3. import android.content.Context;  
  4. import android.content.res.TypedArray;  
  5. import android.util.AttributeSet;  
  6. import android.view.LayoutInflater;  
  7. import android.view.View;  
  8. import android.widget.FrameLayout;  
  9. import android.widget.ImageView;  
  10. import android.widget.TextView;  
  11.   
  12. /** 
  13.  * 繼承已有的ViewGroup 自定義View的實例,經常使用item佈局 
  14.  */  
  15.   
  16. public class MyCustomItemLayout extends FrameLayout {  
  17.     private Context mContext;  
  18.   
  19.     private String mLeftText;  
  20.     private int mRightImageResourceId;  
  21.     private String mRightText;  
  22.     private TextView mTxt_left;  
  23.     private TextView mTxt_right;  
  24.     private ImageView mImg_right;  
  25.   
  26.     public void setLeftText(String leftText) {  
  27.         mLeftText = leftText;  
  28.     }  
  29.   
  30.     public void setRightImageResourceId(int rightImageResourceId) {  
  31.         mRightImageResourceId = rightImageResourceId;  
  32.     }  
  33.   
  34.     public void setRightText(String rightText) {  
  35.         mRightText = rightText;  
  36.     }  
  37.   
  38.     public MyCustomItemLayout(Context context) {  
  39.         this(context,null);  
  40.     }  
  41.   
  42.     public MyCustomItemLayout(Context context, AttributeSet attrs) {  
  43.         this(context, attrs,0);  
  44.     }  
  45.   
  46.     public MyCustomItemLayout(Context context, AttributeSet attrs, int defStyleAttr) {  
  47.         super(context, attrs, defStyleAttr);  
  48.         this.mContext = context;  
  49.   
  50.         //取出自定義屬性  
  51.         TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCustomItemLayout);  
  52.         mLeftText = typedArray.getString(R.styleable.MyCustomItemLayout_leftText);  
  53.         //默認圖片爲箭頭  
  54.         mRightImageResourceId = typedArray.getResourceId(R.styleable.MyCustomItemLayout_rightImage, R.drawable.ic_arrow_right);  
  55.         mRightText = typedArray.getString(R.styleable.MyCustomItemLayout_rightText);  
  56.         typedArray.recycle();  //回收釋放資源  
  57.   
  58.         initView();  
  59.   
  60.         initData();  
  61.     }  
  62.   
  63.     private void initData() {  
  64.         //兩種初始化數據的方法,  外界經過set方法進行設置; 佈局中直接定義  
  65.         mTxt_left.setText(mLeftText);  
  66.         mTxt_right.setText(mRightText);  
  67.         mImg_right.setImageResource(mRightImageResourceId);  
  68.     }  
  69.   
  70.     private void initView() {  
  71.         //注意  這第二個參數傳 this;  兩個參數的方法默認會調用三個參數的方法,  第二個參數不爲null時,至關於三個參數中root不爲null,attach爲true  
  72.         View view = LayoutInflater.from(mContext).inflate(R.layout.layout_customitem, this);  
  73.         mTxt_left = (TextView) findViewById(R.id.txt_left);  
  74.         mTxt_right = (TextView) findViewById(R.id.txt_right);  
  75.         mImg_right = (ImageView) findViewById(R.id.img_right);  
  76.     }  
  77.   
  78.   
  79. }  


首先自定義一個類,繼承自 FrameLayout,固然,這裏你也能夠選擇繼承 LinearLayout 或者其餘,根據具體需求來。其中在構造中獲取了自定義屬性,最主要的地方就是填充佈局那裏,將佈局填充到了當前控件也就是自定義的 ViewGroup 上。填充的佈局以下:
[html] view plain copy

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.               android:layout_width="match_parent"  
  4.               android:layout_height="wrap_content"  
  5.               android:background="?android:selectableItemBackground"  
  6.               android:gravity="center_vertical"  
  7.               android:padding="15dp">  
  8.   
  9.     <TextView  
  10.         android:id="@+id/txt_left"  
  11.         android:layout_width="wrap_content"  
  12.         android:layout_height="wrap_content"  
  13.         android:drawablePadding="5dp"  
  14.         android:ellipsize="end"  
  15.         android:maxLines="1"  
  16.         android:textColor="@color/text_black"  
  17.         android:textSize="@dimen/txt14"/>  
  18.   
  19.     <TextView  
  20.         android:id="@+id/txt_right"  
  21.         android:layout_width="0dp"  
  22.         android:layout_height="wrap_content"  
  23.         android:layout_marginLeft="10dp"  
  24.         android:layout_weight="1"  
  25.         android:ellipsize="end"  
  26.         android:gravity="right"  
  27.         android:maxLines="1"  
  28.         android:textSize="@dimen/txt14"/>  
  29.   
  30.     <ImageView  
  31.         android:id="@+id/img_right"  
  32.         android:layout_width="wrap_content"  
  33.         android:layout_height="wrap_content"  
  34.         android:layout_marginLeft="5dp"  
  35.         android:src="@mipmap/ic_arrow_right"/>  
  36. </LinearLayout>  


 

在項目中 有相相似的Item佈局的使用時, 能夠直接在佈局中經過自定義屬性設置數據:

[html] view plain copy

  1. <com.example.mycustomviewdemo.MyCustomItemLayout  
  2.        android:layout_width="match_parent"  
  3.        android:layout_height="wrap_content"  
  4.        android:layout_marginTop="10dp"  
  5.        app:leftText="版本更新"  
  6.        app:rightText="V1.1"  
  7.        app:rightImage="@drawable/ic_arrow_right"  
  8.        />  

也能夠經過暴露的方法設置數據
 

 

至此,自定義控件四種繼承方式講解完畢,  下面看一三個自定義控件的效果

 

相關文章
相關標籤/搜索