Android 报错:Binary XML file line #10: Error inflating class ***

问题描述

自定义控件的时候,报错Binary XML file line #10: Error inflating class ***

原因

XML中自定义view的标签的格式是 包名 + . + 类名,在XML中引入自定义控件的时候,自定义控件一定要实现相应的构造方法:

构造方法说明:

第一个是用来在代码中创建View使用,第二个和第三个是从xml中创建View时使用,自定义View时这三个构造函数都要实现。

  1. View(Context context) //Simple constructor to use when creating a view from code

  2. View(Context context, AttributeSet attrs) //Constructor that is called when inflating a view from XML

  3. View(Context context, AttributeSet attrs, int defStyle) //Perform inflation from XML and apply a class-specific base style

解决方案:

添加三种构造方法

public MyButton(Context context) {
        super(context);
    }

    public MyButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

在XML中引用:

 <com.dream.fly.selfview.MyButton
        android:id="@+id/btnIn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="点击"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

猜你喜欢

转载自blog.csdn.net/sinat_29675423/article/details/85259448