2013-07-26 53 views
0

在我的活動中,我有一個自定義控件。在的onCreate我膨脹活動的看法按正常的:在Android中充氣自定義控件

setContentView(R.layout.image_viewer); 

這裏是我的xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <MyCustomImageView 
    android:id="@+id/tivImage" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" /> 

</LinearLayout> 

這裏是代碼爲MyCustomTextView減少的一塊:

public class MyCustomImageView extends ImageView 
{ 
    Context context; 

    public MyCustomImageView(Context context) 
    { 
    super(context); 
    sharedConstructing(context); 
    } 

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

異常生成的讀數爲:

android.view.InflateException: Binary XML file line #7: Error inflating class MyCustomImageView 
+0

您是否生成像超類的構造函數? – minipif

+2

您發佈的XML不是您正在使用的XML,因爲您在爲「MyCustomImageView」充氣時出現錯誤,而您的XML包含「MyCustomTextView」。請在更正中修改。 –

+0

對不起,我更正了上面的代碼。我把它粘貼到SO裏的時候改了名字。它確實是MyCustomImageView。感謝您指出,但我仍然有問題。 – AndroidDev

回答

4

您需要添加的軟件包名稱:

<com.my.package.MyCustomTextView 
    android:id="@+id/tivImage" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" /> 
+0

我認爲Android在嘗試使用您的應用程序的默認包名稱時,無法找出源自哪裏的東西。顯然這不是事實。 – AndroidDev

0

你必須創建構造函數調用父類的構造函數,因爲他們將充氣被稱爲:

public class MyView extends View { 

    public MyView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     // TODO Auto-generated constructor stub 
    } 

    public MyView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     // TODO Auto-generated constructor stub 
    } 

    public MyView(Context context) { 
     super(context); 
     // TODO Auto-generated constructor stub 
    } 

} 

而且你必須把完整的包在您的XML名稱:

<com.mypackagename.MyView 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" /> 
相關問題