自定义View的基本知识和步骤

本文介绍如何从零开始创建自定义View,包括定义属性、构造函数、测量尺寸、绘制图形等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义View的基本知识和步骤

原创  2016年04月01日 10:34:53
  • 1156

当初刚入门Android时用的都是原生的控件,刚开始觉得原生的控件其实也可以满足当时的一些学校的小项目开发,也就没怎么深入自定义view。但参加工作后,发现有时美工给的设计图某些功能实现起来还是挺刁钻的,于是便开始了自定义view的学习。或许很多人都觉得自定义view是个很难的东西,其实当你真正用心去弄了几个自定义view之后就会发现其实也并没有那么难。由于个人工作效率还是蛮快的,项目之余闲蛋疼的很,常常自己看到那些好玩的东西就用自定义view画下来。

自定义view的基本步骤无非也就那么几步:

1. values文件夹下创建attrs.xml文件,在attrs里添加你想给自己view添加的属性。例:

attrs.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <declare-styleable name="MyTextView">  
  4.         <attr name="text" format="string"/>  
  5.         <attr name="textSize" format="dimension"/>  
  6.     </declare-styleable>  
  7. </resources>  
declare-styleable是你自定义view的一套新定义的属性,下面包含了你要定义的各种属性attr

format是指定attr属性的单位,其中包括:

(1) reference: 引用某一资源,如:src="@drawable/sourcename";

(2)color:颜色,如color="#ff0000";

(3)boolean:布尔值,true或false;

(4)dimension:尺寸值,如sp,dp,px;

(5)float:浮点型,也就是小数,如0.5, 1.8;

(6)integer:整形, 如 1, 100;

(7)string:字符串

(8)fraction:百分数, 如100%

(9)enum:枚举,如 orientation="vertical"

(10)flag:位或运算,如gravity="centerHorizontal | right"

format的详细格式可以参考这


2. 创建类文件,添加构造体,获取属性并初始化变量。例:

[java]  view plain  copy
  1. public class MyTextView extends View {  
  2.       
  3.     private String text;  
  4.     private int textSize;  
  5.     private Paint paint;  
  6.   
  7.     public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {  
  8.         super(context, attrs, defStyleAttr);  
  9.         // TODO Auto-generated constructor stub  
  10.           
  11.         //顾名思义,获取风格和属性,得到一个包含各种属性的数组array,包括你自定义的attr属性  
  12.         //R.styleable.MyTextView就是一个指向你刚在attrs.xml中自定义的属性数组的id  
  13.         TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.MyTextView);  
  14.           
  15.         //获取文本内容  
  16.         text=array.getString(R.styleable.MyTextView_text);  
  17.           
  18.         //获取文本字体大小,第二个参数是默认值,就是没有使用你定义属性时的提供值, sp2px()是sp转px函数。  
  19.         textSize=array.getDimensionPixelSize(R.styleable.MyTextView_textSize, sp2px(18));  
  20.           
  21.         //这玩意初始化完成后务必回收  
  22.         array.recycle();  
  23.           
  24.         //画笔初始化,用于后面的绘图;  
  25.         paint=new Paint();  
  26.           
  27.         //至此,完成变量的初始化  
  28.     }  
  29.   
  30.     public MyTextView(Context context, AttributeSet attrs) {  
  31.         this(context, attrs, 0);  
  32.         // TODO Auto-generated constructor stub  
  33.           
  34.         //若使用xml加载view,必须要重写上面或这个构造体  
  35.     }  
  36.   
  37.     public MyTextView(Context context) {  
  38.         this(context, null);  
  39.         // TODO Auto-generated constructor stub  
  40.           
  41.         //统一到第一个构造体进行初始化  
  42.     }  
  43. }  

3. 重写onMeasure(),,测量view,确定view的尺寸。(这步并不是自定义view的必要步骤,但重写后可以适应wrap_content这参数等)

这一步因为不是必须,可以跳过,但当你在设置layout_width和layout_height的时候只能设match_parent或指定值,不然设置wrap_content会很别扭。

[java]  view plain  copy
  1. @Override  
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  3.     // TODO Auto-generated method stub  
  4.       
  5.     //widthMeasureSpec参数可以被MeasureSpec类的静态方法解析出宽度计算的模式和值  
  6.     //模式有AT_MOST, EXACTLY, UNSPECIFIED  
  7.     int width=measureViewWidth(widthMeasureSpec);  
  8.       
  9.     //计算高度,和宽度处理差不多  
  10.     int height=measureViewHeight(heightMeasureSpec);  
  11.       
  12.     setMeasuredDimension(width, height);  
  13. }  
  14.   
  15. //处理view的宽度  
  16. private int measureViewWidth(int widthSpec){  
  17.     int result=0;  
  18.       
  19.     int mode=MeasureSpec.getMode(widthSpec);  
  20.     int width=MeasureSpec.getSize(widthSpec);  
  21.       
  22.     //对应wrap_content, viewgroup只提供一个最大值,子view尺寸不能超过这个值  
  23.     //这种情况下,可以根据内容大小设置view的大小,如令view的width=text的宽度  
  24.     if(mode==MeasureSpec.AT_MOST){  
  25.         int textWidth=measureTextWidth();  
  26.         result=Math.min(textWidth, width);  
  27.     }  
  28.     //对应match_parent或指定的值,viewgourp提供的值为parent的宽度或指定的宽度  
  29.     if(mode==MeasureSpec.EXACTLY){  
  30.         result=width;  
  31.     }  
  32.               
  33.     return result;  
  34. }  
  35.   
  36. //处理view的高度  
  37. private int measureViewHeight(int heightSpec){  
  38.     int result=0;  
  39.       
  40.     int mode=MeasureSpec.getMode(heightSpec);  
  41.     int height=MeasureSpec.getSize(heightSpec);  
  42.       
  43.     if(mode==MeasureSpec.AT_MOST){  
  44.         int textHeight=measureTextHeight();  
  45.         result=Math.min(textHeight, height);  
  46.     }  
  47.     if(mode==MeasureSpec.EXACTLY){  
  48.         result=height;  
  49.     }  
  50.   
  51.     return result;  
  52. }  
  53.   
  54. //测量text的宽度  
  55. private int measureTextWidth(){  
  56.     int textWidth=(int) paint.measureText(text);          
  57.     return textWidth;  
  58. }  
  59.   
  60. //测量text的高度  
  61. private int measureTextHeight(){  
  62.     FontMetrics fm=paint.getFontMetrics();  
  63.     int textHeight=(int) (fm.bottom-fm.top);  
  64.     return textHeight;  
  65. }  

widthMeasureSpec和heightMeasureSpec两个值是viewgroup传给子view的,通过MeasureSpec的解析后再根据模式来计算最后的值,若是wrap_content则计算view内容的尺寸再计算view的尺寸,若是match_parent或指定值,则直接使用viewgroup传过来的值,经过处理后,最后还要调用setMeasuredDimension来确定view的最终尺寸。

             

view的尺寸设置为wrap_content情况下,左边没有重写onMeasure,viewgroup会传一个父组件可分配给子view的最大尺寸,所以子view的尺寸便和父容器一样大了;而右边的重写了onMeasure之后,因为经过处理,使子view尺寸等于文本内容大小,所以尺寸只有文本大小。


4.重写onDraw(), 在一块空白的View上绘制你想要的东西,这一步是最重要的。如:

[java]  view plain  copy
  1. @Override  
  2. protected void onDraw(Canvas canvas) {  
  3.     // TODO Auto-generated method stub  
  4.       
  5.     //把view的背景绘成黄色  
  6.     canvas.drawColor(Color.YELLOW);  
  7.       
  8.     //测量绘制字体的高度  
  9.     FontMetrics fm=paint.getFontMetrics();  
  10.     int textHeight=(int) (fm.bottom-fm.top);  
  11.       
  12.     //参数1.要绘制的文本, 2.文本左边位于view的x坐标, 3.文本baseline位于view的y坐标, 4.画笔  
  13.     //因为baseline到文本底部的距离无法获取,只能取文本高度的3/10  
  14.     canvas.drawText(text, 0, textHeight-textHeight*0.3f, paint);  
  15. }  

canvas类封装了一大堆绘图工具,所以画图并不是很难的事,不过若要实现比较复杂的图,那就需要懂得一些几何计算知识了,此处只是把文本简单地画上去而已。

还有那个文本的高度处理不懂的可以百度搜索android baseline或android测量字体高度。


5. 在布局文件里使用,记得添加属性使用的空间,也就是最顶部xmlns=xxxxxx,那一串东西。

activity_main.xml

[html]  view plain  copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:custom="http://schemas.android.com/apk/res/com.example.test"  
  3.     android:id="@+id/layout"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:orientation="vertical">  
  7.      
  8.     <com.example.test.MyTextView   
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         custom:text="aaaaaaaaaaagggggggggggggggg"  
  12.         custom:textSize="18sp"/>  
  13.   
  14. </LinearLayout>  

  

下面的custom属性命名空间必须加上xmlns:custom="http://schemas.android.com/apk/res/com.example.test"才能用

格式:  xmlns:定义的空间名称="http://schemas.android.com/apk/res/在AndroidManifest中的包名。


  

  

至此,一个简单的自定义view就实现了,看起来代码挺多的,但真正去把它写完后,就感觉其实自定义view也就这样而已。当然,简单的view只要实现以上几个步骤,基本就可以满足需要了,如果要实现华丽的效果,仅仅是上面几个步骤不够的, 还要重新onTouchEvent等函数,使view能处理触摸事件从而达到交互效果。

下面贴出完整代码:

MyTextView.java

[java]  view plain  copy
  1. public class MyTextView extends View {  
  2.       
  3.     private String text;  
  4.     private int textSize;  
  5.     private Paint paint;  
  6.   
  7.     public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {  
  8.         super(context, attrs, defStyleAttr);  
  9.         // TODO Auto-generated constructor stub  
  10.           
  11.         //顾名思义,获取风格和属性,得到一个包含各种属性的数组array,包括你自定义的attr属性  
  12.         //R.styleable.MyTextView就是一个指向你刚在attrs.xml中自定义的属性数组的id  
  13.         TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.MyTextView);  
  14.           
  15.         //获取文本内容  
  16.         text=array.getString(R.styleable.MyTextView_text);  
  17.           
  18.         //获取文本字体大小,第二个参数是默认值,就是没有使用你定义属性时的提供值, sp2px()是sp转px函数。  
  19.         textSize=array.getDimensionPixelSize(R.styleable.MyTextView_textSize, sp2px(18));  
  20.           
  21.         //这玩意初始化完成后务必回收  
  22.         array.recycle();  
  23.           
  24.         //画笔初始化,用于后面的绘图;  
  25.         paint=new Paint();  
  26.           
  27.         //至此,完成变量的初始化  
  28.         paint.setTextSize(textSize);  
  29.     }  
  30.   
  31.     public MyTextView(Context context, AttributeSet attrs) {  
  32.         this(context, attrs, 0);  
  33.         // TODO Auto-generated constructor stub  
  34.           
  35.         //若使用xml加载view,必须要重写上面或这个构造体  
  36.     }  
  37.   
  38.     public MyTextView(Context context) {  
  39.         this(context, null);  
  40.         // TODO Auto-generated constructor stub  
  41.           
  42.         //统一到第一个构造体进行初始化  
  43.     }  
  44.   
  45.     @Override  
  46.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  47.         // TODO Auto-generated method stub  
  48.           
  49.         //widthMeasureSpec参数可以被MeasureSpec类的静态方法解析出宽度计算的模式和值  
  50.         //模式有AT_MOST, EXACTLY, UNSPECIFIED  
  51.         int width=measureViewWidth(widthMeasureSpec);  
  52.           
  53.         //计算高度,和宽度处理差不多  
  54.         int height=measureViewHeight(heightMeasureSpec);  
  55.           
  56.         setMeasuredDimension(width, height);  
  57.     }  
  58.       
  59.     //处理view的宽度  
  60.     private int measureViewWidth(int widthSpec){  
  61.         int result=0;  
  62.           
  63.         int mode=MeasureSpec.getMode(widthSpec);  
  64.         int width=MeasureSpec.getSize(widthSpec);  
  65.           
  66.         //对应wrap_content, viewgroup只提供一个最大值,子view尺寸不能超过这个值  
  67.         //这种情况下,可以根据内容大小设置view的大小,如令view的width=text的宽度  
  68.         if(mode==MeasureSpec.AT_MOST){  
  69.             int textWidth=measureTextWidth();  
  70.             result=Math.min(textWidth, width);  
  71.         }  
  72.         //对应match_parent或指定的值,viewgourp提供的值为parent的宽度或指定的宽度  
  73.         if(mode==MeasureSpec.EXACTLY){  
  74.             result=width;  
  75.         }  
  76.                   
  77.         return result;  
  78.     }  
  79.       
  80.     //处理view的高度  
  81.     private int measureViewHeight(int heightSpec){  
  82.         int result=0;  
  83.           
  84.         int mode=MeasureSpec.getMode(heightSpec);  
  85.         int height=MeasureSpec.getSize(heightSpec);  
  86.           
  87.         if(mode==MeasureSpec.AT_MOST){  
  88.             int textHeight=measureTextHeight();  
  89.             result=Math.min(textHeight, height);  
  90.         }  
  91.         if(mode==MeasureSpec.EXACTLY){  
  92.             result=height;  
  93.         }  
  94.       
  95.         return result;  
  96.     }  
  97.       
  98.     //测量text的宽度  
  99.     private int measureTextWidth(){  
  100.         int textWidth=(int) paint.measureText(text);          
  101.         return textWidth;  
  102.     }  
  103.       
  104.     //测量text的高度  
  105.     private int measureTextHeight(){  
  106.         FontMetrics fm=paint.getFontMetrics();  
  107.         int textHeight=(int) (fm.bottom-fm.top);  
  108.         return textHeight;  
  109.     }  
  110.   
  111.     @Override  
  112.     protected void onDraw(Canvas canvas) {  
  113.         // TODO Auto-generated method stub  
  114.           
  115.         //把view的背景绘成黄色  
  116.         canvas.drawColor(Color.YELLOW);  
  117.           
  118.         //测量绘制字体的高度  
  119.         FontMetrics fm=paint.getFontMetrics();  
  120.         int textHeight=(int) (fm.bottom-fm.top);  
  121.           
  122.         //参数1.要绘制的文本, 2.文本左边位于view的x坐标, 3.文本baseline位于view的y坐标, 4.画笔  
  123.         //因为baseline到文本底部的距离无法获取,只能取文本高度的3/10  
  124.         canvas.drawText(text, 0, textHeight-textHeight*0.3f, paint);  
  125.     }  
  126.       
  127.       
  128.     //sp转px单位  
  129.     private int sp2px(int sp){  
  130.         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics());  
  131.     }  
  132.   
  133. }  

布局文件很简单就不贴了, attrs文件也很简单,在上面了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值