问题描述
自定义控件的时候,报错Binary XML file line #10: Error inflating class ***
原因
XML中自定义view的标签的格式是 包名 + . + 类名,在XML中引入自定义控件的时候,自定义控件一定要实现相应的构造方法:
构造方法说明:
第一个是用来在代码中创建View使用,第二个和第三个是从xml中创建View时使用,自定义View时这三个构造函数都要实现。
-
View(Context context) //Simple constructor to use when creating a view from code
-
View(Context context, AttributeSet attrs) //Constructor that is called when inflating a view from XML
-
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" />