2010-07-31 44 views
5

我想爲Android創建一個簡單的3D應用程序,該應用程序將在OpenGL視圖(與API演示中的SurfaceViewOverlay示例非常相似)上分層添加視圖。我遇到了一個試圖用擴展的GLSurfaceView類實現該方法的問題。我已經設置了一個示例,我正在嘗試將this demo與API Oerlay演示相結合。如果我嘗試轉換爲這樣的馬丁的VortexView對象(替換API演示線44-46)Android OpenGL擴展GLSurfaceView空指針異常

VortexView glSurfaceView= 
    (VortexView) findViewById(R.id.glsurfaceview); 

我得到一個ClassCastException錯誤(這是可以理解的,因爲我認爲鑄造是相當具體的),所以我猜想我正在尋找一種方法來將視圖從GLSurfaceView實例轉移到新的子類,或者將一個子類的創建後的渲染表面設置爲XML定義的視圖。

編輯: 我已經取得了一些進展試圖得到這個工作 - 在API例如 認爲XML使用 (從ApiDemos/RES /佈局/ surface_view_overlay.xml)

 <android.opengl.GLSurfaceView android:id="@+id/glsurfaceview" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" /> 

如果我將該元素更改爲
com.domain.project.VortexView 它將使用上面的代碼正確執行轉換,但在命中surfaceCreated和surfaceChanged例程時生成空指針異常(我認爲它是GLThread類中的調用方法基於行號)在GLSurfaceView類中。所以,也許我應該改變這個問題 - 如何在不生成surfaceCreated和surfaceChanged上的NullPointerExceptions的情況下實現GLSurfaceView的擴展,或者如何調試它們而無需GLSurfaceView.java的源代碼?

回答

1

以下是我得到它的工作:

在XML文件中(我的是main.xml中)使用擴展的類規範

 <com.domain.project.VortexView android:id="@+id/vortexview" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" /> 

在您的活動類:

setContentView(R.layout.main); 
    VortexRenderer _renderer=new VortexRenderer();   // setup our renderer 
    VortexView glSurface=(VortexView) findViewById(R.id.vortexview); // use the xml to set the view 
    glSurface.setRenderer(_renderer); // MUST BE RIGHT HERE, NOT in the class definition, not after any other calls (see GLSurfaceView.java for related notes) 
    glSurface.showRenderer(_renderer); // allows us to access the renderer instance for touch events, etc 

視圖定義(VortexView.java):

public class VortexView extends GLSurfaceView { 
    public VortexRenderer _renderer; // just a placeholder for now 

public VortexView(Context context) { // default constructor 
    super(context); 
} 


public VortexView(Context context, AttributeSet attrs) { /*IMPORTANT - this is the constructor that is used when you send your view ID in the main activity */ 
    super(context, attrs); 
} 

public void showRenderer(VortexRenderer renderer){ // sets our local object to the one created in the main activity, a poor man's getRenderer 
    this._renderer=renderer;   
} 

public boolean onTouchEvent(final MotionEvent event) { // An example touchevent from the vortex demo 
    queueEvent(new Runnable() { 
     public void run() { 
      _renderer.setColor(event.getX()/getWidth(), event.getY()/getHeight(), 1.0f); 
     } 
    }); 
    return true; 
} 

}

VortexRenderer.java只是典型的onSurfaceXXXXX調用。

無論如何,這似乎允許我通過擴展的GLSurface來堆棧其他XML定義的視圖,這正是我想要的。

乾杯!

+0

感謝這幫了我。您應該將問題標記爲已回答 – stealthcopter 2011-01-24 22:25:33

+0

已標記,謝謝。很高興有幫助。 – 2011-03-21 23:07:07