⟩⟩ 在项目结构中,导航到 activity_main.xml 并将以下代码粘贴到您的布局中。
<com.google.android.gms.ads.NativeExpressAdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="320x300"
ads:adUnitId="@string/ad_unit_id">
</com.google.android.gms.ads.NativeExpressAdView>
在同一个文件中,即activity_main.xml,在标题部分添加下面的代码行
xmlns:ads="http://schemas.android.com/apk/res-auto"
⟩⟩ 现在打开 MainActivity.java 并在公共类中添加以下代码行
private static String LOG_TAG = "EXAMPLE";
NativeExpressAdView mAdView;
VideoController mVideoController;
⟩⟩ 然后在 MainActivity.java 下,在 onCreate() 方法中添加下面几行代码。
// Locate the NativeExpressAdView.
mAdView = (NativeExpressAdView) findViewById(R.id.adView);
// Set its video options.
mAdView.setVideoOptions(new VideoOptions.Builder()
.setStartMuted(true)
.build());
// The VideoController can be used to get lifecycle events and info about an ad's video
// asset. One will always be returned by getVideoController, even if the ad has no video
// asset.
mVideoController = mAdView.getVideoController();
mVideoController.setVideoLifecycleCallbacks(new VideoController.VideoLifecycleCallbacks() {
@Override
public void onVideoEnd() {
Log.d(LOG_TAG, "Video playback is finished.");
super.onVideoEnd();
}
});
// Set an AdListener for the AdView, so the Activity can take action when an ad has finished
// loading.
mAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
if (mVideoController.hasVideoContent()) {
Log.d(LOG_TAG, "Received an ad that contains a video asset.");
} else {
Log.d(LOG_TAG, "Received an ad that does not contain a video asset.");
}
}
});
mAdView.loadAd(new AdRequest.Builder().build());
⟩⟩ 现在打开 values 文件夹中的 string.xml 文件并粘贴下面的代码行。
<string name="ad_unit_id">ca-app-pub-39402560999xxxxx/21772xxxxx</string>
⟩⟩ 然后打开 Manifest 文件并为其添加 Internet 权限。
<uses-permission android:name="android.permission.INTERNET" />
资源 : How to insert AdMob Native Ad in your Android App