自定义View的简单实现

继承View后实现构造方法,并在其获取自定义的属性值:

 res/values/ 目录下添加一个 attrs.xml ,:

<resources>
    <declare-styleable name="MyView">
        <attr name="content1" format="string" />
        <attr name="isShow1" format="boolean" />
        <attr name="background1" format="color" />
        <attr name="select1" >
            <flag name="s1" value="1"/>
            <flag name="s2" value="2"/>
            <flag name="s3" value="3"/>
        </attr>
    </declare-styleable>
</resources>

构造方法获取:

public MyView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);

    init(context,attrs);
}
private void init(Context context,AttributeSet attrs) {
    TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.MyView);
    if(typedArray != null){
        //这里要注意,String类型是没有默认值的,所以必须定义好,不然又是空指针大法
        mContent = typedArray.getString(R.styleable.MyView_content1);
        mIsShow = typedArray.getBoolean(R.styleable.MyView_isShow1, true);
        mBackground = typedArray.getColor(R.styleable.MyView_background1, Color.RED);
        mSelect = typedArray.getInt(R.styleable.MyView_select1, 0);
        Log.d("viewStyle","content:"+mContent);
        Log.d("viewStyle","isShow:"+mIsShow);
        Log.d("viewStyle","background:"+mBackground);
        Log.d("viewStyle","select:"+mSelect);
    }
}

复写onMesure方法:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    setMeasuredDimension(getSize(widthMeasureSpec),getSize(heightMeasureSpec));
}



private int getSize(int measureSpec) {
    int result = 0;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);
    switch (specMode){
        case MeasureSpec.EXACTLY:
            //当layout_width与layout_height match_parent 为固定数值走这里
            result = 200;
            break;
        case MeasureSpec.AT_MOST:
            //当layout_width与layout_height定义为 wrap_content 就走这里
            result = Math.min(100,specSize);
            break;
        case MeasureSpec.UNSPECIFIED:
            //如果没有指定大小
            result = 400;
            break;
    }
    return result;
}

最后复写onDraw方法,把它画出来:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    Paint paint = new Paint();
    canvas.drawCircle(50, 50, 50, paint);
}

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值