1

我有這樣一個類:自定義視圖不能在XML佈局實例化

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 

什麼問題?

+0

你確定你把確切的包裹? –

+0

是, 包是:test.example.myfirstapp, 活動是:OpenGlActivity, 類是:MyOpenGlView, – Navid777

回答

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