Constructor-related issues in custom View

When customizing View, don't write a single constructor, okay?

no.

Compilation fails. Will prompt:

Why can't the compilation pass?
Is there no default constructor in View? ctrl+F12 to see:

The no-argument constructor does not support app usage and is only used for testing. And the access right is default.
So, indeed there is no default constructor available. All other constructors have parameters.

This is inherited constructor knowledge. If the parent class has a parameterized constructor, but there is no default constructor, the subclass must add a constructor to explicitly call the parent class constructor.

A custom View must write a constructor, with how many parameters?

take two. This article: The purpose of the three constructors of the custom View is that the two-parameter constructor will be used when xml is parsed to generate a View object.

Don't worry, test it:

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);
    }
}

Layout file: 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>

final effect:

Guess you like

Origin blog.csdn.net/zhangjin1120/article/details/131111661