Programatically set the AdMob id String

2019-05-31 08:55发布

问题:

I have several apps I am working on which use common XML interface elements. One of these elements loads AdMob. I can duplicate the element in each project and put the unique ID for each app in the duplicated XML file but I am wondering if there is some way to programatically set the ID string from the application while keeping the XML and not having to duplicate it in each project.

Something akin to:

    setContentView(R.layout.main);
    AdView aView = (AdView)findViewById(R.id.admob);
    aView.<method goes here that sets ads:adUnitId>

I know that instead of instantiating AdMob from the XML, I can do that programatically, or that I can copy main.xml to each project and modify the IDs there, rather than using the one in my library. But I would be happier with a solution similar to my sample code above which lets me keep the AdMob code in main.xml and doesn't make me update main.xml in n places when it changes.

I have been unable to find a class reference or complete description for the deliverables that come with AdMob, and auto complete does not show me any method which would seem to fit this need. If anybody would point me to a place which does have a good description of the AdMob classes, that would be a great help.

回答1:

Set an empty place holder View (ListView for this example) for the AdView in your XML, and then add the AdView programmatically in Java, something like:

ListView lv = (ListView)findViewById(R.id.adplaceholder);

//create the AdView (replace MY_BANNER_UNIT_ID with the admob ID of your choice)
AdView av = new AdView(this, AdSize.BANNER, MY_BANNER_UNIT_ID);
lv.addView(av);//add the AdView to your layout

AdRequest request = new AdRequest();
adView.loadAd(request); 


回答2:

I did following

  1. In your library project add in the string.xml an element with value "" that represent the adUnitId.

    <string name="ad_unit_id"></string>`
    
  2. In your layout insert the adView with

    ads:adUnitId="@string/ad_unit_id"`
    
  3. In your other project(s) add in the string.xml the same element with the current adunitId

    <string name="ad_unit_id">XXXXXXXXXXXXXXXXX</string>`
    

Enjoy :)