如何使用代码创建一个admob智能横幅?我的布局完全是用代码构建的。
答案 0 :(得分:24)
你可以或多或少地这样做:
LinearLayout adContainer = <container>;
AdView adView = new AdView(activity)
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId(<your-publisher-id>);
// Initiate a generic request to load it with an ad
AdRequest adRequest = new AdRequest();
adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
adView.loadAd(adRequest);
// Place the ad view.
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
adContainer.addView(adView, params);
干杯
答案 1 :(得分:0)
在活动
中添加此内容//Add this in OnCreate of Activity to initialize the ad
MobileAds.initialize(getApplicationContext(), "< your-ad-unit-Id >");
//Add this wherever your code needs to add the ad
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
//Additionally to adjust the position to Bottom
layout.setGravity(Gravity.BOTTOM);
// Create a banner ad
mAdView = new AdView(this);
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.setAdUnitId("<your-ad-unit-Id>");
// Create an ad request.
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
// Optionally populate the ad request builder.
adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
// Add the AdView to the view hierarchy.
layout.addView(mAdView);
// Start loading the ad.
mAdView.loadAd(adRequestBuilder.build());
setContentView(layout);
然后检查您是否已在清单
中授予权限 <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
在里面添加元数据&lt;申请&gt;在清单
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
最后检查是否添加了必需的依赖以在 app gradle中进行编译
compile 'com.google.android.gms:play-services:9.6.1'