2014-12-20 29 views
1
interstitial = new InterstitialAd(HomeFragment.this); 

代码上面的部分是给我下面的错误:麻烦加入AdMob广告横幅到我的片段扩展分类

The constructor InterstitialAd(HomeFragment) is undefined 

这是我HomeFragment.java文件:

package info.example.test; 
import com.google.android.gms.ads.AdListener; 
import com.google.android.gms.ads.AdRequest; 
import com.google.android.gms.ads.AdView; 
import com.google.android.gms.ads.InterstitialAd; 
import android.annotation.SuppressLint; 
import android.app.Fragment; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.webkit.WebView; 
import android.app.Activity; 

@SuppressLint("SetJavaScriptEnabled") public class HomeFragment extend Fragment { 

    private InterstitialAd interstitial; 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

     View rootView = inflater.inflate(R.layout.fragment_home, container, false); 

     WebView webView = (WebView)rootView.findViewById(R.id.webView); 
     webView.setInitialScale(1); 
     webView.getSettings().setJavaScriptEnabled(true); 
     webView.getSettings().setLoadWithOverviewMode(true); 
     webView.getSettings().setUseWideViewPort(true); 
     webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); 
     webView.setScrollbarFadingEnabled(false); 
     webView.loadUrl("http://www.company.com"); 

     return rootView; 

     // Prepare the Interstitial Ad 
     interstitial = new InterstitialAd(HomeFragment.this); 
     // Insert the Ad Unit ID 
     interstitial.setAdUnitId("ca-app-pub-455255552555555551543028"); 

     //Locate the Banner Ad in activity_main.xml 
     AdView adView = (AdView) this.findViewById(R.id.adView); 

     // Request for Ads 
     AdRequest adRequest = new AdRequest.Builder() 

     // Add a test device to show Test Ads 
     .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) 
     .addTestDevice("CC5F2555555555555A198") 
     .build(); 

     // Load ads into Banner Ads 
     adView.loadAd(adRequest); 

     // Load ads into Interstitial Ads 
     interstitial.loadAd(adRequest); 

     // Prepare an Interstitial Ad Listener 
     interstitial.setAdListener(new AdListener() { 
      public void onAdLoaded() { 
       // Call displayInterstitial() function 
       displayInterstitial(); 
      } 
     }); 
    } 
    private AdView findViewById(int adview) { 
     // TODO Auto-generated method stub 
     return null; 
    } 
    public void displayInterstitial() { 
     // If Ads are loaded, show Interstitial else show nothing. 
     if (interstitial.isLoaded()) { 
      interstitial.show(); 
     } 
    } 
} 

回答

1

你正在使用片段,这就是为什么你必须使用getContext()而不是this来处理上下文。

变化

interstitial = new InterstitialAd(HomeFragment.this); 

interstitial = new InterstitialAd(rootView.getContext()); 

所以做这一变化,并把AdMob的代码rootView一部分。