Using AdMob from within a Fragment?

2020-07-28 11:20发布

I've begun working on a new application and I decided to start this one off using Fragments via the v13 Support package so I can build one app that does both phone & tablet designs.

I have my AdMob ads working from within a Fragment if I do the creation of them from within the XML file, however, if I try to create them via code I'm running into issues.

public class Fragment_Admob extends Fragment implements AdListener 
{

    private static final String LOG_TAG = "Fragment_Admob";

    private AdView adView;

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

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.admob_view, container, false);

        // Create an ad.
        adView = new AdView(this, AdSize.BANNER, "My_AdMob_Code");

        ...
    }

    ...
}

Eclipse tells me:

The constructor AdView(Fragment_Admob, AdSize, String) is undefined

so I was like ok that makes sense as AdView expects an Activity and not a Fragment. So I tried making the class extend FragmentActivity instead of Fragment and that resolved that particular issue. However now I have fragment expansion issues at runtime which I've worked through before but I am unable to resolve here because I really don't think I'm supposed to use FragmentActivity in a non-activity set of code.

1条回答
【Aperson】
2楼-- · 2020-07-28 12:03

I realized I was going about it all wrong trying to put an ad inside of a Fragment. I instead made my class extend FragmentActivity and then made my layout a RelativeLayout and injected a new RelativeLayout at the bottom with the correct gravity to make it stick. The Fragments then reside inside of the RelativeLayout and get sized accordingly.

public class MyClass extends FragmentActivity implements AdListener 
{
    // Create an ad.
    adView = new AdView(this, AdSize.SMART_BANNER, "MY_ID");
    // Set the AdListener.
    adView.setAdListener(this);
    // Add the AdView to the view hierarchy. The view will have no size until the ad is loaded.
    RelativeLayout layout = (RelativeLayout) findViewById(R.id.home_layout);
    RelativeLayout.LayoutParams adsParams =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    adsParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    layout.addView(adView,adsParams);
    AdRequest adRequest = new AdRequest();
    adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
    // Start loading the ad in the background.
    adView.loadAd(adRequest);
}
查看更多
登录 后发表回答