概述
- Android的自定义View算是比较重要但是又比较难的,因为他涉及的View的绘制,事件传递等比较复杂的知识。
- 自定义View主要有两种类型(我自己接触到),一个是一个ViewGroup,把一些View继承起来,封装起来使用,比如TopBarView,这种比较简单,一般不需要重新onMeasure等方法,第二个是需要自己去自定义一些属性,重写onMeasure等方法实现自己需要的效果。
我们本文主要是主要是第二种。
流程
- 自定义我们需要的属性
- 继承我们需要对应的View,继承View对应的三个(四个)构造方法
- 重写我们需要对应的方法,比如onMeasure,onDraw,onLayout等方法
- 在xml布局文件中使用
实现
自定义属性
a. attr标签 ,定义单个属性<attr name="customText" format="string" />
b. declare-styleable定义属性组
<declare-styleable name="Customize"> <attr name="custom_text4" format="string" /> <attr name="custom_text5" format="string" /> <attr name="custom_sytle" format="reference" /> </declare-styleable>
c. 相关说明:
attr:定义一个属性,name是属性的名称,定义之后可以在属性中使用,可以被多个属性组使用,同一个属性组不能有同名的属性。
declare-styleable:一个属性组,被View中读取,可以是多个属性或者是一个属性的组合,name是指明属性组的名字,在属性组中引入外面单独定义的属性是:<declare-styleable name="myCustomAttrs1"> <attr name="customText" /> </declare-styleable>
d. 属性的格式说明,即format的值类型有:
1,reference 引用,比如引入drawable资源文件,引用color资源等
2,color 颜色值,16进制的
3,boolean 布尔值
4,dimension 尺寸
5,float 浮点数
6,integer 整型
7,string 字符串
8,fraction 百分数
9,enum 枚举类
10,位或运算- View的构造方法:
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
他们的调用:
第一个:直接使用Java代码new一个View实例的时候被调用
第二个:在xml定义的时候一般调用这个
第三个:第三个不是系统调用而是我们自己通过前面两个显示的调用第三个,第三个的作用是可以设置一些默认的样式给我们自定义的View,两种情况下可以生效:
第一:通过设置theme,添加我们对应需要的style作为item,添加到作为application的them
第二,在他的构造函数中,设置默认的style: context.obtainStyledAttributes(attrs, R.styleable.Customize, defStyleAttr, R.style.DefaultCustomizeStyle);
我们的一般使用时第一个构造函数调用第二个,第二个调用第三个,第三个真正执行。
- View的测量模式
测量是我们需要重写onMeasure方法的时候使用到,有三中:
EXACTLY:一般是设置了明确的值,比如20dp那样子或者是MATCH_PARENT
AT_MOST:表示子布局限制在一个最大值内,一般为WARP_CONTENT
UNSPECIFIED:表示子布局想要多大就多大,很少使用
测量模式是在onMeasure中进行测量调用的,根据不同的模式给出不同的测量值,最后通过setMeasuredDimension(width, height);设置回去,这样子就完成了测量。
获取MeasureSpec类型:
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
widthMeasureSpec是onMeasure传入的参数,然后,我们针对获取的widthMode进行真实的width设置,widthSize是目前View的宽度:
//match或者是自定义
if (widthMode == MeasureSpec.EXACTLY)
{
width = widthSize;
} else
{
int desired = (int) (getPaddingLeft() + width + getPaddingRight());
width = desired;
}
对于widh,除了EXACTLY(match_parent或者是指定尺寸,这时候 )的之外,width就是左右的pandding+自身的宽度,就OK了, heigh同样的道理,然后,通过:
setMeasuredDimension(width, height);
设置回去,这样子就完成了测量。
3. View的绘制
就是onDraw方法,传入一个画布,自己对需要的东西就在这个画布上面画出来,比如text,比如bitmap等