android-----自定义View实现系列(一)

转载自:http://blog.csdn.net/hzw19920329/article/details/51533987

         在 Android 开发中,我们和View打交道的机会是最多的,那么问题来了,平常你所使用的View基本上都是系统自带的,如果某一天项目中需要一些特殊的View控件的话,你就不得不实现自己的View了,那么你至少就需要了解View到底是怎么绘制、怎么显示的了,鉴于View的绘制源码比较难懂,接下来的几篇博客,我会首先从应用的角度来实现一些自定义View的小Demo,之后简单分析下源码,能力有限,望有不对的地方赐教,小弟不胜感激;

        如果按照类型划分的话,自定义View的实现方式大概有三种,自绘控件、组合控件、继承控件;

        这篇主要实现的是自绘控件:http://write.blog.csdn.net/postedit/51533987

        创建自定义View的步骤:

        (1)继承View或者View的派生子类:

        必须提供能够获取Context和作为属性的AttributeSet类型对象的构造函数,当View从XML布局中创建之后,XML标签中的所有属性都从资源包中读取出来并且作为一个AttributeSet传递给View的构造函数;

        我们来看看View派生类:

   

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class TimerCountDownView extends View{  
  2.   
  3.     public Paint paint;  
  4.     public Rect rect;  
  5.     public int count = 10;  
  6.       
  7.     public TimerCountDownView(Context context) {  
  8.         super(context);  
  9.     }  
  10.   
  11.     public TimerCountDownView(Context context, AttributeSet attrs) {  
  12.         super(context, attrs);  
  13.         paint = new Paint(Paint.ANTI_ALIAS_FLAG);//使位图抗锯齿  
  14.         rect = new Rect();//创建矩形  
  15.     }  
  16.       
  17.     public TimerCountDownView(Context context, AttributeSet attrs, int defStyle) {  
  18.         super(context, attrs, defStyle);  
  19.     }  
  20. }  

        我们来说说这三种构造函数什么时候会得到调用:

        第一个:一般View view = new View(context);的时候被调用;

        第二个:当我们在xml布局文件中使用View时,会在inflate布局时调用,如:

     <View layout_width="match_parent" layout_height="match_parent"/>。

       第三种:跟第二种类似,但是增加Style属性设置

       <View style="@styles/MyCustomStyle" layout_width="match_parent" layout_height="match_parent"/>。

       因为本示例我们是要在xml中使用自定义View,所以第二个构造函数是必须需要的;

        (2)定义自定义属性:

         一个良好的自定义控件应该是通过xml来进行控制的,所以我们应该考虑下我们自定义的View中哪些属性可以被提取到xml中,通常是在资源元素<declare-styleable>中为View定义自定义属性,需要在项目中添加<declare-styleable>资源,这些资源存放在res/values/attrs.xml文件中,其中attrs这个文件的名字可以是任意的;

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <resources>  
  2.     <declare-styleable name="TimerCountDownView">  
  3.         <attr name="rectColor" format="color"/>  
  4.         <attr name="paintColor" format="color"/>  
  5.         <attr name="textSize" format="integer"/>  
  6.    </declare-styleable>  
  7. </resources>  
        我们为每一个attr结点都写了name和format属性,format是name属性所对应的数据结构,合法的值包括string,color,dimension,boolean,integer,float,enum;

        一旦定义了自定义属性,我们便可以在xml文件中进行使用,唯一区别就是需要引入我们自定义的命名空间,引入方式有两种:

        一种是在根布局中进行命名空间的声明,在根布局中添加xmlns:http://schemas.android.com/apk/res/[你的自定义View所在的包路径]

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:myview="http://schemas.android.com/apk/res-auto"<!-xmlns:myview="http://schemas.android.com/apk/com.hzw.myownviewtest"-->  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent">  
  6.     <com.hzw.myownviewtest.TimerCountDownView  
  7.         android:id="@+id/view"  
  8.         android:layout_width="50dp"  
  9.         android:layout_height="50dp"  
  10.         myview:rectColor="#FFE4E1"  
  11.         myview:paintColor="#F0FFFF"   
  12.         myview:textSize="30"  
  13.         android:layout_centerInParent="true"/>   
  14. </RelativeLayout>  

        可能你的编译器会报:No resource identifier found for attribute 'paintColor' in package这个错误,解决方法是将命名空间的路径修改为xmlns:http://schemas.android.com/apk/res-auto,原因在于ADT升级之后,系统会对自定义控件的命名空间的路径进行优化;

        另一种是在自定义View上定义命名空间:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"    
  4.     android:layout_height="match_parent">  
  5.     <com.hzw.myownviewtest.TimerCountDownView  
  6.         xmlns:myview="http://schemas.android.com/apk/res-auto"<!-xmlns:myview="http://schemas.android.com/apk/com.hzw.myownviewtest"-->  
  7.         android:id="@+id/view"  
  8.         android:layout_width="50dp"  
  9.         android:layout_height="50dp"  
  10.         myview:rectColor="#FFE4E1"  
  11.         myview:paintColor="#F0FFFF"   
  12.         myview:textSize="30"  
  13.         android:layout_centerInParent="true"/>   
  14. </RelativeLayout>  
       (3)应用自定义属性:

        在上面,我们已经通过xml设定了自定义属性rectColor和paintColor,当View从xml布局中创建之后,xml标签中的所有属性都从资源包中读取出来并作为AttributeSet传递给了View的构造函数,尽管我们可以从AttributeSet中直接读取出里面的属性值,但是这样做有一些缺点,比如带有值的资源引用没有进行处理、样式并没有得到允许之类的,那么为了想要提取属性,我们就需要用到TypedArray类和obtainStyledAttributes方法,将AttributeSet传递给obtainStyledAttributes方法,这个方法会返回一个TypedArray数组,有了这个数组我们就可以获取里面的属性啦;

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1.        public int rectColor;  
  2. public int paintColor;  
  3.        public int textSize;  
  4.   
  5.       public TimerCountDownView(Context context) {  
  6.     super(context);  
  7. }  
  8.   
  9. public TimerCountDownView(Context context, AttributeSet attrs) {  
  10.     super(context, attrs);  
  11.     paint = new Paint(Paint.ANTI_ALIAS_FLAG);//使位图抗锯齿  
  12.     rect = new Rect();//创建矩形  
  13.     setupAttributes(attrs);  
  14.      }  
  15.   
  16. public TimerCountDownView(Context context, AttributeSet attrs, int defStyle) {  
  17.     super(context, attrs, defStyle);  
  18. }  
  19.   
  20.   
  21. /** 
  22.  * 读取我们自定义的属性值 
  23.  * @param attrs 
  24.  */  
  25. public void setupAttributes(AttributeSet attrs)  
  26. {  
  27.     //提取自定义属性到TypeArray对象中  
  28.     TypedArray ta = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.TimerCountDownView, 00);  
  29.     try {  
  30.         rectColor = ta.getColor(R.styleable.TimerCountDownView_rectColor, Color.BLACK);  
  31.         paintColor = ta.getColor(R.styleable.TimerCountDownView_paintColor, Color.BLACK);  
  32.                        textSize = ta.getInteger(R.styleable.TimerCountDownView_textSize, 20);  
  33.                   }finally {  
  34.         //TypeArray对象是共享的,必须被重复利用  
  35.         ta.recycle();  
  36.     }  
  37. }  

        (4)添加属性的setter和getter方法:

        属性是用来控制View的行为以及外观的,但是只有在View初始化之后,属性才可读,为了提供动态的行为,需要暴露每个自定义属性的一对getter和setter方法:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1.     public int getRectColor() {  
  2.         return rectColor;  
  3.     }  
  4.   
  5.     public void setRectColor(int rectColor) {  
  6.         this.rectColor = rectColor;  
  7.         invalidate();  
  8.         requestLayout();  
  9.     }  
  10.   
  11.     public int getPaintColor() {  
  12.         return paintColor;  
  13.     }  
  14.   
  15.     public void setPaintColor(int paintColor) {  
  16.         this.paintColor = paintColor;  
  17.         invalidate();  
  18.         requestLayout();  
  19.     }  
  20.         public int getTextSize() {  
  21.         return textSize;  
  22.     }  
  23.   
  24.      public void setTextSize(int textSize) {  
  25.         this.textSize = textSize;  
  26.         invalidate();  
  27.         requestLayout();  
  28.     }  
        当View的属性发生变化之后我们需要重绘View以及重新布局,一定要确保调用了invalidate()和requestLayout()

        (5)自定义绘制(onDraw(canvas))

        绘制视图最重要的一步就是重写onDraw方法了,这个方法有一个Canvas类型的参数,Canvas可以理解成你想画什么,Paint可以理解成你想怎么画,比如想要画一个矩形,那么Canvas用于决定你所画矩形的大小位置等,而Paint用于决定你所画矩形的背景色等;

        好了,下面我们通过自定义一个倒计时控件来运用一下上面介绍的步骤:

        首先是我们的自定义View----TimerCountDownView,他继承自View:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class TimerCountDownView extends View{  
  2.   
  3.     public Paint paint;  
  4.     public Rect rect;  
  5.     public int count = 10;  
  6.     public int rectColor;  
  7.     public int paintColor;  
  8.     public int textSize;  
  9.       
  10.     public TimerCountDownView(Context context) {  
  11.         super(context);  
  12.     }  
  13.   
  14.     public TimerCountDownView(Context context, AttributeSet attrs) {  
  15.         super(context, attrs);  
  16.         paint = new Paint(Paint.ANTI_ALIAS_FLAG);//使位图抗锯齿  
  17.         rect = new Rect();//创建矩形  
  18.         setupAttributes(attrs);  
  19.     }  
  20.       
  21.     public TimerCountDownView(Context context, AttributeSet attrs, int defStyle) {  
  22.         super(context, attrs, defStyle);  
  23.     }  
  24.       
  25.       
  26.     /** 
  27.      * 读取我们自定义的属性值 
  28.      * @param attrs 
  29.      */  
  30.     public void setupAttributes(AttributeSet attrs)  
  31.     {  
  32.         //提取自定义属性到TypeArray对象中  
  33.         TypedArray ta = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.TimerCountDownView, 00);  
  34.         try {  
  35.             rectColor = ta.getColor(R.styleable.TimerCountDownView_rectColor, Color.BLACK);  
  36.             paintColor = ta.getColor(R.styleable.TimerCountDownView_paintColor, Color.BLACK);  
  37.             textSize = ta.getInteger(R.styleable.TimerCountDownView_textSize, 20);  
  38.         }finally {  
  39.             //TypeArray对象是共享的,必须被重复利用  
  40.             ta.recycle();  
  41.         }  
  42.     }  
  43.       
  44.     @Override  
  45.     protected void onDraw(Canvas canvas) {  
  46.         super.onDraw(canvas);  
  47.         paint.setColor(rectColor);//设置背景色  
  48.         canvas.drawRect(00, getWidth(), getHeight(), paint);  
  49.         paint.setColor(paintColor);  
  50.         paint.setTextSize(textSize);//设置字体大小  
  51.         String text = String.valueOf(count);  
  52.         paint.getTextBounds(text, 0, text.length(), rect);  
  53.         float textWidth = rect.width();  
  54.         float textHeight = rect.height();  
  55.         canvas.drawText(text, getWidth()/2-textWidth/2, getHeight()/2+textHeight/2, paint);  
  56.     }  
  57.       
  58.     /** 
  59.      * 设置View上面需要显示的值 
  60.      * @param count 
  61.      */  
  62.     public void setCount(int count)  
  63.     {  
  64.         this.count = count;  
  65.         invalidate();//表示重绘制View  
  66.     }  
  67.   
  68.     public int getRectColor() {  
  69.         return rectColor;  
  70.     }  
  71.   
  72.     public void setRectColor(int rectColor) {  
  73.         this.rectColor = rectColor;  
  74.         invalidate();  
  75.         requestLayout();  
  76.     }  
  77.   
  78.     public int getPaintColor() {  
  79.         return paintColor;  
  80.     }  
  81.   
  82.     public void setPaintColor(int paintColor) {  
  83.         this.paintColor = paintColor;  
  84.         invalidate();  
  85.         requestLayout();  
  86.     }  
  87.   
  88.     public int getTextSize() {  
  89.         return textSize;  
  90.     }  
  91.   
  92.     public void setTextSize(int textSize) {  
  93.         this.textSize = textSize;  
  94.         invalidate();  
  95.         requestLayout();  
  96.     }  
  97. }  

        第30行的setupAttributes方法用于获取我们自定义的属性值,首先通过obtainStyledAttributes获取到我们在xml文件中设置的自定义属性数组,注意获取到这些值的前提条件是对于我们的自定义属性,必须提供其对应的set和get方法,也就是从68到96行的部分,注意在每个属性的set方法中需要调用invalidate来进行View的重绘,调用requestLayout来进行视图的重绘,获取我们自定义属性方法的第二个参数是假如我们不设置某个属性类型的话,默认的属性值,比如第35行的ta.getColor方法,第二个参数Color.BLACK指的是当我们在xml中不设置rectColor属性的情况下,rectColor的默认值是Color.BLACK,注意在第40行,使用完TypeArray之后要对其进行回收处理;

        第45行的onDraw用于在View上面绘制矩形,比较简单;

        接下来就是我们的MainActivity了:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class MainActivity extends Activity {  
  2.   
  3.     public Handler mHandler;  
  4.     public int count = 10;  
  5.     public TimerCountDownView myView;  
  6.       
  7.     @Override  
  8.     protected void onCreate(Bundle savedInstanceState) {  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.activity_main);  
  11.         myView = (TimerCountDownView) findViewById(R.id.view);  
  12.         TimeThread thread = new TimeThread();  
  13.         thread.start();  
  14.         mHandler = new Handler(){  
  15.             @Override  
  16.             public void handleMessage(Message msg) {  
  17.                 switch (msg.what) {  
  18.                 case 0:  
  19.                     count = msg.getData().getInt("count");  
  20.                     myView.setCount(count);  
  21.                     break;  
  22.   
  23.                 default:  
  24.                     break;  
  25.                 }  
  26.             }  
  27.         };  
  28.     }  
  29.     class TimeThread extends Thread  
  30.     {  
  31.         @Override  
  32.         public void run() {  
  33.             while(true)  
  34.             {  
  35.                 try {  
  36.                     Thread.sleep(500);  
  37.                 } catch (InterruptedException e) {  
  38.                     e.printStackTrace();  
  39.                 }  
  40.                 count = count - 1;  
  41.                 if(count == 0)  
  42.                     count = 10;  
  43.                 Message message = new Message();  
  44.                 Bundle bundle = new Bundle();  
  45.                 bundle.putInt("count", count);  
  46.                 message.setData(bundle);  
  47.                 message.what = 0;  
  48.                 mHandler.sendMessage(message);  
  49.             }  
  50.         }  
  51.     }  
  52. }  
        我们采用Handler来每隔500ms更新矩形上面显示的值达到倒计时的目的,代码相对简单,不做过多解释;

        点击下载源码!!!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值