我想将广告整合到我的应用中,但问题是应用崩溃了,当我将广告添加到片段而不是活动时。
有谁能告诉我它的工作代码?
我尝试了一些方法,但它们没有用。如果代码放在活动中,它可以正常工作
以下是我为Fragment尝试的代码:
//it shows error in get application content and find view by id
// so I added get activity() and get view() to it
MobileAds.initialize(getActivity().getApplicationContext(), "ca-app-pub-xxxxxxxxxxxxx~33xxxxxxx");
AdView mAdView = (AdView) getView().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
答案 0 :(得分:1)
试试这个,我认为你将adView放在片段的xml(布局)中
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.your_fragment_layout, container, false);
MobileAds.initialize(getActivity(), "ca-app-pub-xxxxxxxxxxxxx~33xxxxxxx");
AdView mAdView = (AdView) v.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
return v;
}
答案 1 :(得分:0)
获取膨胀的view
,并以此为参考来查找并绑定您的adView
@Override
public void onStart() {
super.onStart();
View view = getView();
if (view != null){
AdView mAdView = (AdView) view.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().addTestDevice().build();
mAdView.loadAd(adRequest);
}
}