我无法在Android应用上加载广告,我已经给出了正确的ID,一切都是正确的。这是代码
public class MainActivity extends Activity {
private static final String MY_BANNER_UNIT_ID = "a15264b25a5a98c";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rel);
AdView adView = new AdView(this, AdSize.BANNER, MY_BANNER_UNIT_ID);
layout.addView(adView);
AdRequest request = new AdRequest();
request.setTesting(true);
adView.loadAd(request);
}
}
XML文件是
<com.example.advertise.AdView
xmlns:googleads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/ad"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
googleads:adSize="BANNER"
googleads:adUnitId="a15264b25a5a98c"
/>
我得到的错误是
10-21 11:51:15.194: E/AndroidRuntime(8556): FATAL EXCEPTION: main
10-21 11:51:15.194: E/AndroidRuntime(8556): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidadvertising/com.example.androidadvertising.MainActivity}: android.view.InflateException: Binary XML file line #12: Error inflating class com.example.advertise.AdView
10-21 11:51:15.194: E/AndroidRuntime(8556): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
10-21 11:51:15.194: E/AndroidRuntime(8556): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
答案 0 :(得分:1)
试试这个,使用布局inflater,你会得到它
public class MainActivity extends Activity {
private static final String MY_BANNER_UNIT_ID = "a15264b25a5a98c";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rel);
//Try this
LayoutInflater li = LayoutInflater.from(YourActivity.this);
View v = li.inflate(R.layout.youraddmoblayout,null,false);
layout.addView(v);
AdRequest request = new AdRequest();
request.setTesting(true);
adView.loadAd(request);
}
}
像这样的Youraddmoblayout.xml
<com.google.ads.AdView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
ads:adSize="BANNER"
ads:adUnitId="@string/adMob"
ads:loadAdOnCreate="true" >
</com.google.ads.AdView>
答案 1 :(得分:1)
将此行添加到XML文件的主布局
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads
<com.google.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
ads:adSize="BANNER"
ads:adUnitId="@string/adMob" <--YOUR ID HERE
ads:loadAdOnCreate="true" >
</com.google.ads.AdView>
并将此行添加到 AndroidManifeast.xml
<activity android:name="com.google.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation" />
不需要java代码......