Android开发:《Gradle Recipes for Android》阅读笔记(翻译)3.4——Flavor Dimensions

问题:

一个product flavor不够,你需要另一个标准去区分不同版本的app

解决方案:

在product flavor中增加flavorDimensions

讨论:

在3.2章展示了一个有三个product flavor的app(arrogant,friendly,obsequious)。这几个flavor是基于态度区分。

然后不同的客户希望app有他们自己的烙印。代码大体上都是一样的。只有很小的一部分不一样。

为了防止大量的赋值黏贴,介绍下额外的flavor dimension。build file如下:

flavorDimensions 'attitude', 'client'
productFlavors {
    arrogant {
        dimension 'attitude'
        applicationId 'com.oreilly.helloworld.arrg'
    }
    friendly {
        dimension 'attitude'
        applicationId 'com.oreilly.helloworld.frnd'
    }
    obsequious {
        dimension 'attitude'
        applicationId 'com.oreilly.helloworld.obsq'
    }
    stark {
        dimension 'client'
    } 
wayne { dimension 'client' } }

现在有两个不同维度的flavor:attitude和client。arrogant,friendly和obsequious是基于态度的,stark和wayne是对不同的客户。

这形成更多的变体。

为了让这些变体做些可见的事情,为每个客户 flavor新增目录结构,如下:

stark客户stark/res/values目录下的colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="text_color">#beba46</color> 
  <color name="background_color">#771414</color> </resources>

wayne/res/values目录下的colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="text_color">#beba46</color>
    <color name="background_color">#771414</color> 
</resources>

不同客户下的string.xml就改变hello_world字符串:

<resources>
  <string name="hello_world">Stark Industries</string>
</resources>
<resources>
    <string name="hello_world">Wayne Enterprises</string>
</resources>

acitivity_main.xml里面的TextView被修改使用心得colors和strings。

<TextView
android:id="@+id/name_text_view" 
android:layout_width
="match_parent"
android:layout_height
="wrap_content"
android:textColor
="@color/text_color"
android:background
="@color/background_color"
android:textSize
="32sp"
android:text
="@string/hello_world" />

效果如下图:

有一个需要注意的地方。flavorDimension标签中将attitude放在client前面,以为这attitude里面的值比client里面的优先级高。因此将hello_world字符串从每个attitude flavor中去除。交换client和attitude的顺序也是这样工作。

原文地址:https://www.cnblogs.com/tootwo2/p/6399529.html