给Android程序添加不同的广告平台

本文假设已有一个广告,比如admob,然后添加另一广告,比如有米,用来在根据不同的语言自动调用不同的广告平台。

  1. 在attrs.xml中追加一个declare-stylea,原有的属性不需要再定义。结果如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    < ?xml version="1.0" encoding="UTF-8"?>
    <resources>
    <declare -styleable name="com.admob.android.ads.AdView">
    <attr name="testing" format="boolean" />
    <attr name="backgroundColor" format="color" />
    <attr name="textColor" format="color" />
    <attr name="keywords" format="string" />
    <attr name="refreshInterval" format="integer" />
    <attr name="isGoneWithoutAd" format="boolean" />
    </declare>

    <declare -styleable name="net.youmi.android.AdView">
    <attr name="changeAdAnimation" format="boolean"/>
    <attr name="backgroundTransparent" format="integer"/>
    </declare>
    </resources>
  2. 为不同的区域创建不同的layout
    首先在默认的layout目录中创建ads.xml文件,用于存放广告代码。在工程目录上右击,New->Android XML File,输入文件名ads.xml,结束。
    然后为特定的语言创建ads.xml。在工程目录上右击,New->Android XML File,输入文件名ads.xml选择资源类型为Layout,添加Region为cn,添加Language为zh,结束。

  3. 把针对于非中文的广告配置移动到layout/ads.xml文件中,如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18

    < ?xml version="1.0" encoding="utf-8"?>
    <merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:admobsdk="http://schemas.android.com/apk/res/com.deskangel.dacalc"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <com .admob.android.ads.AdView
    android:id="@+id/ad"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    admobsdk:backgroundColor="#000000"
    admobsdk:textColor="#FFFFFF"
    admobsdk:keywords="Android application"
    admobsdk:refreshInterval="60"
    admobsdk:testing="false"
    />
    </merge>
  4. 把针对中文的广告配置移动到layout-zh-rCN/ads.xml文件中:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    < ?xml version="1.0" encoding="utf-8"?>
    <merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:umadsdk="http://schemas.android.com/apk/res/com.deskangel.dacalc"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <net .youmi.android.AdView
    android:id="@+id/ad"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    umadsdk:refreshInterval="30"
    umadsdk:changeAdAnimation="false"
    umadsdk:backgroundTransparent="255"
    umadsdk:testing="false"
    umadsdk:isGoneWithoutAd="true"
    />
    </merge>
  5. 在需要显示广告的地方添加:

    1
    2
    3
    4
    5
    <include android:layout_height="wrap_content"
    layout="@layout/ads"
    android:id="@+id/incAds"
    android:layout_width="fill_parent" >
    </include>

    大功告成!非常简单的配置。