Android studio中Custom View使用方法

CustomView是自定义View基类,如果你的自定义View继承这个类则能自动获取到View大小与一个默认的Paint,可以帮助你节省部分代码,示例如下:

通常的自定义View

public class MyView extends View {

    private int mWidth;
    private int mHeight;
    private Paint mPaint;

    public MyView(Context context) {
        this(context, null);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 初始化画笔
        mPaint.setColor(Color.GRAY);
    }
    

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 获取View宽高与画笔并根据此绘制内容

        canvas.translate(mWidth / 2, mHeight / 2);
        canvas.drawCircle(0,0,100,mPaint);
    }
}

继承CustomView

public class MyView extends CustomView {

    public MyView(Context context) {
        this(context, null);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 初始化画笔
        mDefaultTextPaint.setColor(Color.GRAY);
    }
    
    
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 获取View宽高与画笔并根据此绘制内容

        canvas.translate(mViewWidth / 2, mViewHeight / 2);
        canvas.drawCircle(0,0,100,mDeafultPaint);
    }
}

Android studio的好处,这里就不错过多的说明了。studio中内置了很多的模版可供使用,大大的简化了工作量。在实际开发中,android自带的各类控件可能无法满足我们的需求,这就需要我们自定义控件,下面介绍一下Custom View的方法。

第一步:studio界面,File->New->UI Component->Custom View,sutdio自动创建一个布局、CustomView类以及一个自定义属性XML。

接下来,由于gradle默认自定义属性为

   xmlns:XXX="http://schemas.android.com/apk/res-auto"形式,来取代 xmlns:XXX="http://schemas.android.com/apk/res/包名"的形式

       所以需要在使用该自定义控件时,在所遇的布局中,手动加上该声明。例如:我在MainActivity的布局中使用该控件,且用到自定义属性,需要在MainActivity的布局声明中添加 xmlns:XXX="http://schemas.android.com/apk/res-auto"后再使用。

    由于自动生成的控件类,在布局中使用时,会调用CustomView(Context context, AttributeSet attrs)构造函数,其中会使用到自定义的某些属性,所以需要在主布局中
添加上相应的自定义属性,或者删除掉相应的调用自定义属性的代码,否则app会因为非法访问崩溃。                                                                                                                                                         

猜你喜欢

转载自blog.csdn.net/qq_29586601/article/details/77851328