首先,加載您的廣告並將其存儲在不在UI片段中的某個位置。我推薦一個保留的片段。然後,從要顯示要求顯示廣告的廣告(即DetailPageFragment)的片段實施回叫。
例子:(我不知道這是否編譯;它更僞代碼)
public class DetailPageFragment extends Fragment {
public interface AdRequestListener {
void onAdRequestedForDisplay();
}
...
public void onAdLoaded(NativeAd ad) {
// Display ad here
}
public void onAttach(Activity activity) {
// Set listener
}
public void onCreateView(Bundle savedInstanceState) {
listener.onAdRequestedForDisplay();
}
}
public class AdLoadingFragment extends Fragment {
private NativeAd ad;
public interface AdLoadListener {
void onAdLoaded(NativeAd ad);
}
public void onAttach(Activity activity) {
try {
this.listener = (AdLoadListener) activity;
} catch(ClassCastException cce) {
throw new RuntimeException(activity.toString() + " must implement AdLoadListener");
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
if(savedInstanceState != null) {
requestAd();
}
}
private void requestAd() {
//Request ad
//Notify listener when ad is loaded
}
public void onAdRequested() {
if(ad != null && listener != null) {
listener.onAdLoaded(ad);
}
}
...
}