转自:http://blog.csdn.net/lmj623565791/article/details/24252901


转载请标明出处: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 , 在里面定义我们的属性和声明我们的整个样式。

[html] view plain copy
  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

[objc] view plain copy
  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="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的构造方法中,获得我们的自定义的样式

[java] view plain copy
  1. /**
  2. *文本
  3. */
  4. privateStringmTitleText;
  5. /**
  6. *文本的颜色
  7. */
  8. privateintmTitleTextColor;
  9. /**
  10. *文本的大小
  11. */
  12. privateintmTitleTextSize;
  13. /**
  14. *绘制时控制文本绘制的范围
  15. */
  16. privateRectmBound;
  17. privatePaintmPaint;
  18. publicCustomTitleView(Contextcontext,AttributeSetattrs)
  19. {
  20. this(context,attrs,0);
  21. }
  22. publicCustomTitleView(Contextcontext)
  23. {
  24. this(context,null);
  25. }
  26. /**
  27. *获得我自定义的样式属性
  28. *
  29. *@paramcontext
  30. *@paramattrs
  31. *@paramdefStyle
  32. */
  33. publicCustomTitleView(Contextcontext,AttributeSetattrs,intdefStyle)
  34. {
  35. super(context,attrs,defStyle);
  36. /**
  37. *获得我们所定义的自定义样式属性
  38. */
  39. TypedArraya=context.getTheme().obtainStyledAttributes(attrs,R.styleable.CustomTitleView,defStyle,0);
  40. intn=a.getIndexCount();
  41. for(inti=0;i<n;i++)
  42. {
  43. intattr=a.getIndex(i);
  44. switch(attr)
  45. {
  46. caseR.styleable.CustomTitleView_titleText:
  47. mTitleText=a.getString(attr);
  48. break;
  49. caseR.styleable.CustomTitleView_titleTextColor:
  50. //默认颜色设置为黑色
  51. mTitleTextColor=a.getColor(attr,Color.BLACK);
  52. break;
  53. caseR.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=newPaint();
  65. mPaint.setTextSize(mTitleTextSize);
  66. //mPaint.setColor(mTitleTextColor);
  67. mBound=newRect();
  68. mPaint.getTextBounds(mTitleText,0,mTitleText.length(),mBound);
  69. }

我们重写了3个构造方法,默认的布局文件调用的是两个参数的构造方法,所以记得让所有的构造调用我们的三个参数的构造,我们在三个参数的构造中获得自定义属性。

3、我们重写onDraw,onMesure调用系统提供的:

[java] view plain copy
  1. @Override
  2. protectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec)
  3. {
  4. super.onMeasure(widthMeasureSpec,heightMeasureSpec);
  5. }
  6. @Override
  7. protectedvoidonDraw(Canvascanvas)
  8. {
  9. mPaint.setColor(Color.YELLOW);
  10. canvas.drawRect(0,0,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代码:

[java] view plain copy
  1. @Override
  2. protectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec)
  3. {
  4. intwidthMode=MeasureSpec.getMode(widthMeasureSpec);
  5. intwidthSize=MeasureSpec.getSize(widthMeasureSpec);
  6. intheightMode=MeasureSpec.getMode(heightMeasureSpec);
  7. intheightSize=MeasureSpec.getSize(heightMeasureSpec);
  8. intwidth;
  9. intheight;
  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. floattextWidth=mBounds.width();
  18. intdesired=(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. floattextHeight=mBounds.height();
  29. intdesired=(int)(getPaddingTop()+textHeight+getPaddingBottom());
  30. height=desired;
  31. }
  32. setMeasuredDimension(width,height);
  33. }

现在我们修改下布局文件:

[html] view plain copy
  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添加一个事件:

在构造中添加:

[java] view plain copy
  1. this.setOnClickListener(newOnClickListener()
  2. {
  3. @Override
  4. publicvoidonClick(Viewv)
  5. {
  6. mTitleText=randomText();
  7. postInvalidate();
  8. }
  9. });

[java] view plain copy
  1. privateStringrandomText()
  2. {
  3. Randomrandom=newRandom();
  4. Set<Integer>set=newHashSet<Integer>();
  5. while(set.size()<4)
  6. {
  7. intrandomInt=random.nextInt(10);
  8. set.add(randomInt);
  9. }
  10. StringBuffersb=newStringBuffer();
  11. for(Integeri:set)
  12. {
  13. sb.append(""+i);
  14. }
  15. returnsb.toString();
  16. }

下面再来运行:


我们添加了一个点击事件,每次让它随机生成一个4位的随机数,有兴趣的可以在onDraw中添加一点噪点,然后改写为验证码,是不是感觉很不错。


更多相关文章

  1. Android(安卓)Studio 中Kotlinx开发
  2. 如何实现Android(安卓)布局背景模糊化处理
  3. View高度动画
  4. Android(安卓)自定义左滑删除列表
  5. Android之属性动画Animator
  6. Android(安卓)popupwindow 示例程序一
  7. android布局全屏显示,状态栏和导航栏透明设置
  8. android中的R中属性获取相关
  9. 使用setContentView的方式更换布局文件从而更换界面

随机推荐

  1. SQL Server 2016里的sys.dm_exec_input_b
  2. SQL Server 2012 身份验证(Authentication
  3. 探讨select in 在postgresql的效率问题
  4. SQL Server 2012 安全概述
  5. SQL数据库存储过程示例解析
  6. sqlserver还原数据库的时候出现提示无法
  7. SQL Server评估期已过问题的解决方法
  8. SQL附加数据库失败问题的解决方法
  9. SQL(MSSQLSERVER)服务启动错误代码3414的
  10. SQL语句性能优化(续)