1. 程式人生 > >Android 報錯:Binary XML file line #10: Error inflating class ***

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" />