如何将颜色资源 ID 的 int 数组从 array.xml 传递到 SwipeRefreshLayout.setColorSchemeResources

How to pass int array of color resource ids from array.xml to SwipeRefreshLayout.setColorSchemeResources

我已经让 Android 的 SwipeRefreshLayout 正常工作,我正在尝试自定义整个应用程序中所有拉动刷新的颜色。为了遵循 DRY 原则,我尝试将所需的颜色移动到 array.xml,如下所示:

<resources>
    <array name="swipeRefreshColors">
        <item>@color/pink</item>
        <item>@color/green</item>
    </array>
</resources>

但是,当我尝试将它们导入滑动刷新时:

swipeRefreshLayout.setColorSchemeResources(R.array.swipeRefreshColors);

我得到一个 Resources$NotFoundException:

android.content.res.Resources$NotFoundException: Resource ID #0x7f060001
            at android.content.res.Resources.getValue(Resources.java:1233)
            at android.content.res.Resources.getColor(Resources.java:887)
            at android.support.v4.widget.SwipeRefreshLayout.setColorSchemeResources(SwipeRefreshLayout.java:477)

我已经尝试了一些方法,例如将 SwipeRefreshLayout 代码子类化并在那里对颜色进行硬编码,但这绝对是一个 hack。必须有一种方法可以从 Activity 中引用一组颜色来自定义它。

如有任何帮助,我们将不胜感激!

原来我遗漏了两个关键部分。

错误代码:

swipeRefreshLayout.setColorSchemeResources(R.array.swipeRefreshColors);

正确代码:

swipeRefreshLayout.setColorSchemeColors(getResources().getIntArray(R.array.swipeRefreshColors));

我遗漏了两件事。

1) 我需要指出我正在从我的 array.xml 文件中获取 IntArray。这是通过 getResources().getIntArray(R.array.swipeRefreshColors) 完成的。

答案已删除,但感谢之前提出此建议的人。

2) 错误的关键部分是我不得不使用 setColorSchemeColors 而不是 setColorSchemeResources。我想在构建过程中的某个时刻,我在 Array 中的引用被转换为明确的颜色值。

希望这对其他人有帮助!