android自定义组件进行布局

时间:2012-10-16 17:58:12

标签: android layout custom-component

我想将自定义ImageView添加到xml布局中。

main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.android.gag.TouchImageView
        android:id="@+id/Image1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:clickable="true"
        android:scaleType="center" />

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

</RelativeLayout>

TouchImageView,顾名思义,extends ImageView类。

Main.java

touchImageView = (TouchImageView)findViewById(R.id.Image1);

我的应用崩溃了。 Logcat输出:

10-16 20:38:20.275: E/AndroidRuntime(11354): FATAL EXCEPTION: main
10-16 20:38:20.275: E/AndroidRuntime(11354): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.gag/com.android.gag.Main}: android.view.InflateException: Binary XML file line #6: Error inflating class com.android.gag.TouchImageView
10-16 20:38:20.275: E/AndroidRuntime(11354):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
idRuntime(11354): Caused by: android.view.InflateException: Binary XML file line #6: Error inflating class com.android.gag.TouchImageView
10-16 20:38:20.275: E/AndroidRuntime(11354):    at android.view.LayoutInflater.createView(LayoutInflater.java:589)
10-16 20:38:20.275: E/AndroidRuntime(11354):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)

拜托,有人可以帮帮我吗? 我是初学者,所以像'replace "class library" with "Android library project"'这样的答案毫无意义,因为它们太模糊,我不知道从哪里开始,到哪里去。

编辑:链接到我的TouchImageView class

1 个答案:

答案 0 :(得分:2)

自定义View类的代码缺少两个构造函数。来自Android docs for the View class

View(Context context, AttributeSet attrs)

从XML扩充视图时调用的构造方法。

View(Context context, AttributeSet attrs, int defStyle)

从XML执行通胀并应用特定于类的基本样式。

它崩溃了,因为它找不到它需要的构造函数,所以它不能给视图充气。

为TouchImageView类实现这两个构造函数,并查看问题是否消失。

相关问题