自定义view(1)

自定义view(一)

转载请注明出处:http://blog.csdn.net/ZhouLi_CSDN/article/details/46504881

自定义属性

使用步骤:
1. 通过<declare-styleable>为自定义View添加属性

2. 在xml中为相应的属性声明属性值

3. 在运行时(一般为构造函数)获取属性值

4. 将获取到的属性值应用到View
在res/values目录下创建attr.xml文件
<?xml version="1.0" encoding="utf-8"?>  
<resources>  

    <attr name="text" format="string" />

    <declare-styleable name="CustomTitleView">  
        <attr name="text" />
    </declare-styleable>  

</resources>

format类型:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;
xml布局文件要引入命名空间:xmlns:custom=”http://schemas.android.com/apk/res/应用包名”
可以参考:[文章]
(http://www.cnblogs.com/angeldevil/p/3479431.html)

获取自定义属性:

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyle, 0);

自定义view三个构造函数:
1. 一个参数的:java代码创建view时调用
2. 两个参数的:在xml创建但是没有指定style的时候调用
3. 三个参数的:在xml创建指定style时调用

重写onMeasure方法:

测量控件和子控件的宽和高并设置
MeasureSpec的三种模式:
1. EXACTLY:一般是设置了明确的值或者是MATCH_PARENT
2. AT_MOST:表示子布局限制在一个最大值内,一般为WARP_CONTENT
3. UNSPECIFIED:表示子布局想要多大就多大,很少使用

@Override  
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
{  
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);  
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);  
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);  
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);  
    int width;  
    int height ;  
    if (widthMode == MeasureSpec.EXACTLY)  
    {  
        width = widthSize;  //直接设置值
    } else  
    {   //根据内容计算大小并设置
        mPaint.setTextSize(mTitleTextSize);  
        mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds);  
        float textWidth = mBounds.width();  
        int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight());  
        width = desired;  
    }
    setMeasuredDimension(width, height);  
}

onLayout:

设置控件和子控件的位置

onDraw:

绘制控件的内容

onDispatchDraw:

也可以绘制,但是在绘制过程中,系统先向下绘制父view的onDraw,然后子view的onDraw ; 之后在反过来向上调用子view的onDispatchDraw,然后是父view的onDispatchDraw。

所以造成的效果是:

  1. 子view的onDraw会覆盖父view的;
  2. 父view的onDispatchDraw会覆盖子view的onDispatchDraw,
  3. 并且onDispatchDraw会覆盖onDraw。