在片段视图中添加 AdMob 横幅广告,可以通过以下步骤完成:
implementation 'com.google.android.gms:play-services-ads:20.4.0'
<FrameLayout
android:id="@+id/adContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:background="@android:color/darker_gray" />
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
public class YourFragment extends Fragment {
private AdView adView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
adView = new AdView(getActivity());
adView.setAdUnitId("YOUR_AD_UNIT_ID");
adView.setAdSize(AdSize.BANNER);
FrameLayout adContainer = view.findViewById(R.id.adContainer);
adContainer.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
return view;
}
@Override
public void onDestroyView() {
if (adView != null) {
adView.destroy();
}
super.onDestroyView();
}
}
确保将 "YOUR_AD_UNIT_ID" 替换为你在 AdMob 平台上创建的广告单元的 ID。
<uses-permission android:name="android.permission.INTERNET" />
这样,当你的片段视图被创建时,AdMob 横幅广告将会显示在片段底部。
推荐的腾讯云相关产品:腾讯广告(https://cloud.tencent.com/product/tga)
领取专属 10元无门槛券
手把手带您无忧上云