自定义视图不能在XML布局实例化 [英] custom view cannot be instantiated in xml layout

查看:436
本文介绍了自定义视图不能在XML布局实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个类:

public class MyOpenGlView extends GLSurfaceView
    {

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

和我想在我的XML布局像这样来声明这个类:

and I want to declare this class in my xml layout like this:

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

但再有就是这个错误在图形布局模式:

but then there is this error in "Graphical Layout" mode :

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

出了什么问题?

what's the problem?

推荐答案

尝试把setRenderer(新MyRenderer()); isInEditMode(),如在

Try putting setRenderer(new MyRenderer()) ; under isInEditMode() like

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

另外,在XML文件尝试更改

Also in your XML File try changing

<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的工作室,并让其自动导入类

if you are using android studio and let it import the class automatically

别的尝试将其更改为

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

这篇关于自定义视图不能在XML布局实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆