自定义View中构造函数相关问题

自定义View时,一个构造函数都不写,行不行?

不行。

编译通不过。会提示:

为什么编译通不过?
View里面没有默认构造器吗?ctrl+F12看下:

那个无参构造函数,不支持app使用,只用于测试。并且访问权限是default。
所以,确实没有可用的默认构造函数。其他构造函数都是有参的。

这是继承的构造函数知识了。父类有有参构造器,但是没有默认构造器时,子类必须添加构造器,显示调用父类构造器。

自定义View必须写构造函数,带几个参数?

带两个。这篇文章:自定义View的三个构造函数的用途中讲了,两个参数的构造函数,在xml解析生成View对象时,会用到。

不放心,实测下:

public class MyView extends View {
    
    

    Paint paint;
    public MyView(Context context, @Nullable AttributeSet attrs) {
    
    
        super(context, attrs);
        paint = new Paint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
    
    
        super.onDraw(canvas);
        canvas.drawCircle(20, 20, 20, paint);
    }
}

布局文件:activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.exp.cpdemo.MyView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="#ff0000"/>

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_centerInParent="true"
       />

</RelativeLayout>

最终效果:

猜你喜欢

转载自blog.csdn.net/zhangjin1120/article/details/131111661