自定义视图无法在xml布局中实例化

时间:2013-01-07 13:03:08

标签: android xml android-layout android-custom-view glsurfaceview

我有一个这样的课程:

public class MyOpenGlView extends GLSurfaceView
    {

        public MyOpenGlView(Context context) {
            super(context);
            setRenderer(new MyRenderer()) ;
        }
    }

我想在我的xml布局中声明这个类,如下所示:

<LinearLayout 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"
    tools:context=".OpenGlActivity" >

    <test.example.myfirstapp.OpenGlActivity.MyOpenGlView android:id = "@+id/myImage"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        />

</LinearLayout>

但是“图形布局”模式中出现此错误:

The following classes could not be instantiated:
- test.example.myfirstapp.OpenGlActivity.MyOpenGlView (Open Class, Show Error Log)
See the Error Log (Window > Show View) for more details.
Tip: Use View.isInEditMode() in your custom views to skip code when shown in Eclipse

有什么问题?

1 个答案:

答案 0 :(得分:1)

尝试使用setRenderer(new MyRenderer());在isInEditMode()之下

if (isInEditMode())
{
 setRenderer(new MyRenderer()) ;
}

同样在您的XML文件中尝试更改

<test.example.myfirstapp.OpenGlActivity.MyOpenGlView android:id = "@+id/myImage"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    />

 <MyOpenGlView android:id = "@+id/myImage"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    />

如果您正在使用android studio并让它自动导入该类

否则尝试将其更改为

<view
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    class="test.example.myfirstapp.OpenGlActivity.MyOpenGlView"
    android:id="@+id/myImage" />
相关问题