如何将linkandroid资源值组合起来?

How to link android resource values together?

我很难找到一种模式来创建指向资源值集合的常量。 假设我在布局的每个角落都有四个 TextView。然后我有四组不同的常量内容随机分配给这四个 TextView。该内容带有文本和 TextView 的背景颜色。这些值在 strings.xml 和 colors.xml 中定义。假设 strings.xml 看起来像这样:

<resources>
    <string name="A">Text for A</string>
    <string name="B">Text for B</string>
    <string name="C">Text for C</string>
    <string name="D">Text for D</string>
</resources>

我的 colors.xml 是这样的:

<resources>
    <color name="A">#AAAAAA</color>
    <color name="B">#BBBBBB</color>
    <color name="C">#CCCCCC</color>
    <color name="D">#DDDDDD</color>
</resources>

在 Activity class 然后我想编写一个方法将这些值随机分配给 TextViews。为此,我可以为每种类型的值创建列表,然后从这四个值中随机选择一个 TextView,从每个列表中删除第一个值并将其分配给 TextView:

List<Integer> colors = Arrays.asList(R.color.A,
                                     R.color.B,
                                     R.color.C,
                                     R.color.D);
List<String> strings = Arrays.asList(R.string.A,
                                     R.string.B,
                                     R.string.C,
                                     R.string.D);

for (int i = 4; i > 0; i--) {
    int randomNumber = // get a random number between 0 and i
    TextView tv = // get text view based on i (by switch case)
    tv.setText(string.remove(0));
    tv.setBackgroundColor(getResources().getColor(colors.remove(0));
}

我觉得这个解决方案不太好,因为乍一看字符串和颜色值之间的关系并不明显。还要写很多代码。 然后我想到了一个枚举,其中每个枚举值都有对其关联资源的引用。

enum TextViewContent {
    A(R.string.A, R.color.A),
    B(R.string.B, R.color.B),
    C(R.string.C, R.color.C),
    D(R.string.D, R.color.D);

    public final String string;
    public final int color;

    private TextViewContent(String string, int color) {
        this.string = string;
        this.color = color;
    }
}

在我看到这个页面 https://android.jlelse.eu/android-performance-avoid-using-enum-on-android-326be0794dc3 之前,我觉得这个解决方案很好,他们建议避免在 android 代码中使用枚举。在该页面的示例中,要避免的枚举都可以用一组基本类型的常量替换。我不确定使用枚举是否仍然是个好主意。另一方面,我运行不知道如何解决这个问题。
在这种情况下使用枚举是最好的解决方案吗?如果不是:最好的解决方案是什么?

以可以用作数组的方式准备资源:

<string-array name="texts">
    <item>Text for A</item>
    <item>Text for B</item>
    <item>Text for C</item>
    <item>Text for D</item>
</string-array>

<color name="A">#AAAAAA</color>
<color name="B">#BBBBBB</color>
<color name="C">#CCCCCC</color>
<color name="D">#DDDDDD</color>

<integer-array name="colors">
    <item>@color/A</item>
    <item>@color/B</item>
    <item>@color/C</item>
    <item>@color/D</item>
</integer-array>

那么你需要做的就是检索它们:

    String[] strings = getResources().getStringArray(R.array.texts);
    int[] colors = getResources().getIntArray(R.array.colors);

编码不多。
它还易于维护,因为如果您想更改文本或颜色,或者添加新项目或删除项目,您只需在资源中工作。
至于字符串和颜色值之间的关系,那就再明显不过了。