Android Adventures - Spinners
Android Adventures - Spinners
Written by Mike James   
Friday, 21 August 2015
Article Index
Android Adventures - Spinners
Item Selection
Dynamic change

ArrayAdapter From Resource

Setting the contents of the Spinner using a String array in code is a good way to see how the Spinner works but it isn't the way it usually happens. 

Android provides a comprehensive system of resources - strings, images and lots of XML files. The idea is that you can produce customized versions of you application just by changing the resource files i.e. without having to modify your code. 

For detailed information on using resources see chapter 9 - Resources

For example in the case of a Spinner you could set up a resource that was a String array that provided the list of items to be displayed. If you then wanted to create a version of your app for a foreign market you could get the list translated and created a resource in the new language. 

Resources are a great idea and you should use them for all fixed strings and fixed data in general. So far the examples have tended to avoid resources to make things simpler but for a Spinner you need to know how to code up a String array resource and use it.

Android Studio does have some good resource support but in some areas it is lacking. For example, in an ideal world the system would help you create a String or String array resource but at the moment it only goes so far. While it does help you create a String resource it does nothing for a String array and we have no choice but work with the XML file. 

That is - at the moment Android Studio only provides help for simple string values. 

Find the file strings.xml in the res/values directory and open the file strings.xml. Add to this the String array definition:

<string-array name="SpinnerList">
 <item>Canada</item>
 <item>Mexico</item>
 <item>USA</item>
</string-array>

The meaning of the XML is obvious  and this is the advantage of a human readable markup language. 

If you have explored resources using the Resource window which appears when you select the three dots option in the properties window you might worry that this new resource i.e. SpinnerList, doesn't appear. It also doesn't appear in the Resource editor that you can select while editing the XML file. 

The reason is that currently Android Studio doesn't support the assignment, editing or creation of String Arrays other than manually.

However making use of the new resource is fairly easy.

To create an ArrayAdapter from a resource you need to make use of a static method of the ArrayAdapter class - createFromResource. This just needs you to specify the context, the resource id and the Spinner layout. All you have to do is to replace the creation of stringArrayAdapter

 

ArrayAdapter<CharSequence> stringArrayAdapter=
 ArrayAdapter.createFromResource(this,
  R.array.SpinnerList,  
  android.R.layout.simple_spinner_dropdown_item); 

With this change everything works as before but now to change the items that appear in the Spinner you simply edit the XML file. 

You could also use the getResources object to retrieve the String array and then proceed as if the String array had been defined in code. 


private String[] country =
 getResources().getStringArray(R.array.SpinnerList);

 

Changing The List

There are lots of more advanced things that you can do with Spinners but these aren't encountered that often - mainly when trying to build a custom user experience. 

The one thing that does occur often is the need to dynamically change the list of items. There are many slight variations on this but essentially what you can do is change the String array and then call the adapter's notifyDataSetChange method. For example if you want to change Mexico, i.e. element one,  to Greenland you would use:

country[1]="Greenland";
stringArrayAdapter.notifyDataSetChanged();

The ArrayAdapter also has an add, clear, remove and an insert method which can be used to modify the underlying data but for this to work the object holding the data has to be modifiable.

You can't modify a String array in this way.

What you need is an ArrayList. 

If you change the declaration of country to:

ArrayList<String> country=new ArrayList<String>(
     Arrays.asList("Canada", "Mexico", "USA"));

You can then add "Greenland" to the end of the items using:

stringArrayAdapter.add("Greenland");

You can always find out how many items there are using the getCount method. 

Notice that in this case the ArrayAdapter constructor used changes from one that accepts an array to one that accepts a List of objects.

How do you modify a list of items that are created using a resource?

This is a tricky question because the ArrayAdapter creates a String array to hold the data which means you can't use the methods that modify a list. 

There are a number of ways of fixing this up but the simplest is perhaps to construct your own ArrayList from the resource directly:

Resources res=getResources();
ArrayList<String> country=new ArrayList<String>(
   Arrays.asList(
   res.getStringArray(R.array.SpinnerList)));
ArrayAdapter<String> stringArrayAdapter=
   new ArrayAdapter<String>(this,
   android.R.layout.simple_spinner_dropdown_item,
   country);

With this version of the ArrayAdapter you can once again use the add and other methods to modify the list of items.

Summary

  • Spinners are a way of presenting a list of options for the user to select from. 

  • Spinners can be complex in terms of their layout and what they show but the simplest example is to work with an array of Strings.

  • The array of Strings can be created in the code or within a resource file.

  • The array of Strings has to be converted into an ArrayAdapter object to be used with the Spinner. 

  • The ArrayAdapter provides a View object for each item displayed in the Spinner.
     
  • There are two ways (at least) to load a String array resource into an ArrayAdapter - using its createFromResource or by loading the resource as String array and then proceeding as before.

  • Loading the String array has the advantage that you can change it into an ArrayList which can be modified in code by adding or deleting elements - you cannot change the length of a String array.

  • To find out what the user has selected simply use the onItemSelected event handler.

  • To retrieve the item that the user has selected use the getItemAtPosition(position) method.

Conclusion 

There is much more to say about the Spinner and how to customize it, but the methods explained here are the most common. If you don't agree email me with a question. 

Moving on from Spinners the next thing you need to know about are Pickers, the topic of the next chapter.

Meanwhile if you have any questions on what we've covered so far please let me know using the comments.

 

You can download the code for this program from the CodeBin.

(Note: you have to register first).

 

 

Android Adventures With Android Studio

cover

Contents

  1. Getting Started With Android Studio
  2. The Activity And The UI
  3. Building The UI and a Calculator App
  4. Basic Controls And Events
  5. Layout Containers
  6. UI Graphics A Deep Dive
  7. Menus & The Action Bar
  8. Menus, Context & Popup
  9. Resources
  10. Beginning Bitmap Graphics
  11. Staying Alive! Lifecycle & State
  12. Spinners
  13. Pickers
  14. ListView And Adapters
  15. Using Android Studio (coming soon)

If you are interested in creating custom template also see:

Custom Projects In Android Studio

Androidgears

 

 

To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter,FacebookGoogle+ or Linkedin,  or sign up for our weekly newsletter.

 

blog comments powered by Disqus

 



Last Updated ( Friday, 21 August 2015 )
 
 
Banner

   
Copyright © 2015 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.