今天編寫一個android加入surfaceview的問題,xml中的代碼如下
<?xml version="1.0" encoding="utf-8" ?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Game.escape.GameService android:id="@+id/myview"android:layout_width="fill_parent"android:layout_height="fill_parent"></Game.escape.GameService> </LinearLayout>
在程式中代碼代碼只有一句就是載入xml:setContentView(R.layout.main);一點點簡單的程式,就報錯了:unable to start activity componentInfo。很明顯就是說acvitity啟動這個surfaceview啟動不了。但是為什麼呢,以前我用過的啊,上網上找了一會,有一篇外國的文章有解決辦法原文如下http://www.coderanch.com/t/521231/Android/Mobile/reading-XML-layout-contains-SurfaceView 勉強看懂了,原來是GameService這個繼承SurfaceView的類只有(Context context)這個建構函式,而沒有(Context context, AttributeSet attrs)這個建構函式,原因如下:
如果你的activity顯示內容就只是一個surfaceview的話,那麼你只重寫public mysurfaceview(Context context)就可以,然後在activity的oncreate方法中使用類似於下面的代碼載入:
setContentView(new MySurfaceView(this));
如果你的SurfaceView是放在一個xml布局檔案中比如main.xml中,那麼你的SurfaceView中只需要重寫public mysurfaceview(Context context, AttributeSet attrs),載入時就要這樣:
setContentView(R.layout.main);
來源:http://www.eoeandroid.com/thread-73010-1-1.html