-2

Recently, I was workin on a project where I have had a Spinner with a small number of values. The values were static, and I stored them into an array in the resources.

<string-array name="my_array">
    <item>Value 1</item>
    <item>Value 2</item>
    <item>Value 3</item>
    <item>Value 4</item>
</string-array>

Populating the Spinner using the ArrayAdapter was pretty straight forward (for more info, check: Android Developer: Spinners), but I know that the Spinner can be also populated by adding android:entries="@array/my_array" in the .xml directly.

ArrayAdapter was always my choice when it comes to populating Spinner, but I'm wondering, what are some best practices, are there any downsides populating such a simple spinner directly in the .xml, because it would make a class with less code, cleaner and more readable?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Aleksandar G
  • 1,163
  • 2
  • 20
  • 25
  • Maybe you are looking for this -> https://stackoverflow.com/questions/4029261/populating-spinner-directly-in-the-layout-xml ? – MrVasilev Sep 06 '18 at 15:18
  • @MrVasilev I've read that post, and at the end of the answer, blindstuff worte: "I've heard this doesn't always work on the designer, but it compiles fine", so I was wondering what are the cases when this solution does not working? – Aleksandar G Sep 06 '18 at 15:39

1 Answers1

1

It depends entirely on your use-case.

Since you're using static values that are all in XML, it's better for you to use the XML option to let Android load the array and create an adapter for you. You know what the values should be, and they're not going to change.

However, say you're making at app that lets the user select which local Google account they want to use to log into your service. One way to do this would be to have a Spinner populated with the user's currently-added Google accounts. Obviously, you can't define these in XML, because you have no idea what they'll be, or when they might change. This is where dynamically loading values and populating the Spinner is useful.

Of course, if you don't want to use XML, or you need a custom adapter, it's also fine to just do it all programmatically.

TheWanderer
  • 16,775
  • 6
  • 49
  • 63
  • Thanks for the answer. So you are saying that there are no downsides using **XML**. I was confused with the last sentence from the answer: https://stackoverflow.com/questions/4029261/populating-spinner-directly-in-the-layout-xml by @blindstuff – Aleksandar G Sep 06 '18 at 15:45
  • I'm saying there _are_ downsides to using XML. Read my third paragraph. They just don't apply to your use-case. The designer is the preview you can use in Android Studio to get an idea of what your layout will look like without actually compiling. – TheWanderer Sep 06 '18 at 15:47