自定义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。
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值