2011-06-06 66 views
1

我是新來的android開發,但我想添加admob到我的應用程序使用surfaceview(panelView - GameView)。Android - Admob SurfaceView

我試過以下http://rx-games.com/admob-adverts-on-surfaceview-no-xml-tutorial/但我一定是做錯了,因爲rl.addView(panelView);添加一個nullPointerException。任何幫助是極大的讚賞。

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    //setContentView(R.layout.main); 
    AdView adView = new AdView(this, AdSize.BANNER, "a14ded47ad3779e"); 
    panelView = (GameView) findViewById(R.id.gameScreen); 

    RelativeLayout rl = new RelativeLayout(this); 
    rl.addView(panelView); 
    rl.addView(adView); 

    setContentView(rl); 

    threadView = panelView.getThread(); 
} 

回答

0

您從xml佈局中膨脹GameView類並將其添加到根視圖中,該視圖不是在同一個xml中定義的視圖。你有兩個選擇:

  1. 您創建SurfaceView完全用Java(如您發佈的例子)

  2. 用戶在使用XML佈局AdView的(我寧願這個選項在另一個)

如果命名xml文件game_layout.xml,您可以使用它作爲:

setContentView(R.layout.game_layout.xml); 

game_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <com.google.ads.AdView 
    android:id="@+id/adView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    ads:adUnitId="@string/admob_id" 
    ads:adSize="BANNER" 
    ads:loadAdOnCreate="true" 
    android:layout_alignParentBotom="true" 
    /> 
    <your.package.GameView 
    android:id="@+id/gameScreen" 
    android:layout_alignParentTop="true" 
    android:layout_above="@id/adView" 
    /> 
</RelativeLayout> 
+0

就像我說的,我很新...我已經有4000+行代碼創建了gameview類。我將如何在xml中調用這個和adView?如果你知道這個教程,那就行了。我不認爲我理解視圖如何工作... – teynon 2011-06-07 00:20:21

+0

@Tom在更新的響應中查看示例。關於教程,我建議你首先閱讀開發指南:http://developer.android.com/guide/topics/ui/index.html – Aleadam 2011-06-07 00:38:45

+0

我標記你爲接受的答案,但我仍然有問題...現在它給我一個運行時錯誤和一個空白屏幕。感謝您的幫助。我在軍隊裏,在自己的閒暇時間裏學習。 – teynon 2011-06-07 01:14:11