首页 > 解决方案 > 在 xml 中设置变量,就像在 android 中为 adMob 设置清单占位符一样

问题描述

文件中的清单占位符build.gradle允许您指定可以在manifest文件中使用的常量,就像这样。

  manifestPlaceholders = [admob_app_id: "ca-app-pub-3940256099942544~3347511713", banner_id: "ca-app-pub-3940256099942544/6300978111"]

然后在清单文件中

 <meta-data
   android:name="com.google.android.gms.ads.APPLICATION_ID"
   android:value="${admob_app_id}" />

这在布局 xml 文件的情况下似乎不起作用

    <com.google.android.gms.ads.AdView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/publisherAdView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    ads:adSize="BANNER"
    ads:adUnitId="${banner_id}" />

有没有办法可以banner id根据构建配置动态更改。我尝试过以编程方式执行此操作,但 admob throws 一直在抱怨,除非两者adSizeadUnitId在 xml 中声明。

标签: androidgradleandroid-gradle-pluginadmobbuild.gradle

解决方案


您可以使用resValue()方法使用您的横幅 id 创建一个字符串资源,然后在您的布局中引用它:

android {
  ...
  buildTypes {
    release {
      resValue("string", "banner_id", "foo")
      ...
    }
    debug {
      resValue("string", "banner_id", "bar")
      ...
    }
  }
}
ads:adUnitId="@string/banner_id"

推荐阅读