如何替换 build.gradle 的 ProductFlavours 中的 string.xml 值

Arc*_*ana 1 xml android

在 strings.xml 中

<resources>
<string>name="app_name">App_Name</string>
<string>name="app_port">https://example.com</string>
<string>name="app_key">App_Key</string>
</resources>
Run Code Online (Sandbox Code Playgroud)

在 build.gradle 中

productFlavors {
    production {
        applicationId = "com.example.production"
    }
    staging {
        applicationId = "com.example.staging"
        //code to manipulate strings.xml value because for production and staging app_name, app_port and key are different
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要一个代码来操作 build.gradle 文件的 ProductFlavours 中的 strings.xml,而不是为暂存和生产创建单独的文件夹。

Arc*_*ana 6

我找到了答案。在 gradle 中使用resValue如下

productFlavors {
production {
    applicationId = "com.example.production"
    resValue 'string', 'APP_NAME', 'app_name'
}
staging {
    applicationId = "com.example.staging"
    resValue 'string', 'APP_NAME', 'app_name_stage'
}
Run Code Online (Sandbox Code Playgroud)

它将在构建目录中创建 generated.xml 文件。要获取代码中的值,请像其他所有资源一样使用生成的资源,如下所示,

getResources().getString(R.string.APP_NAME)
Run Code Online (Sandbox Code Playgroud)