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

1

11

I've got Android's SwipeRefreshLayout working and am trying to customize the colors across all the pull to refreshes throughout the app. In order to follow the DRY principle, I've tried moving the desired colors to array.xml as follows:

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

However, when I try and import them into the swipe to refresh:

swipeRefreshLayout.setColorSchemeResources(R.array.swipeRefreshColors);

I get a 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)

I've tried a couple things such as subclassing the SwipeRefreshLayout code and hard coding the colors there, but it's definitely a hack. There's got to be a way to reference an array of colors from the Activity to customize it.

Any help would be greatly appreciated!

Abran answered 23/1, 2015 at 20:17 Comment(0)
A
18

Turns out I was missing two key pieces.

Wrong Code:

swipeRefreshLayout.setColorSchemeResources(R.array.swipeRefreshColors);

Correct Code:

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

There were two things I was missing.

1) I needed to indicate that I was getting an IntArray from my array.xml file. This is done through getResources().getIntArray(R.array.swipeRefreshColors).

The answer was deleted, but thanks to whoever suggested this before.

2) The key part that was wrong is that I had to use setColorSchemeColors instead of setColorSchemeResources. I guess at some point in the build process the references I had in Array were converted to explicit color values.

Hopefully this can help someone else!

Abran answered 23/1, 2015 at 21:3 Comment(1)
Thanks this helped a lot, I tried this in kotlin and got error saying that an Int is required instead of IntArray. What fixed this for me was adding a star before the array variable so like, *swipeRefreshColors, if you initialise the variable elsewhere. Otherwise I guess it would just be a setColorSchemeColors(*... :)Osis

© 2022 - 2024 — McMap. All rights reserved.