其他分享
首页 > 其他分享> > 自定义View的简单实现

自定义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);
}

 

 

 

 

 

标签:result,自定义,int,简单,styleable,attrs,MyView,typedArray,View
来源: https://blog.csdn.net/qq_37973828/article/details/116094926