Android Adventures - Spinners And Pickers
Written by Mike James   
Thursday, 19 September 2013
Article Index
Android Adventures - Spinners And Pickers
Array Adapter
Dynamic change

onItemSelected

Let's look at the onItemSelected event handler in more detail:

 public void onItemSelected(
  AdapterView<?> parent, 
  View view, 
  int position, 
  long id) {
 }

What is this AdapterView that has suddenly appeared?

All of the visible components of the UI correspond to View objects of one sort or another. An AdapterView is the View object that corresponds to one of the displayed items in the Spinner that the ArrayAdapter is displayed in. You can use the AdapterView passed to the event handler to say modify the look of the displayed item. 

The view parameter is just the child of the AdapterView that was actually clicked - an item can be composed of more than one View item. 

Finally the int position parameter and the long id provide the position of the view that was clicked in the adapter and the row id of the item that was selected.  You can populate a Spinner from a database - in this case the row id gives the database row number - which isn't necessarily the same as its position in the Spinner. For a simple ArrayAdapter the position and id are the same. 

In most cases the only parameter you will be interested in is the int position which gives you the item the user selected. 

For example, place a TextField on the design surface and change the onItemSelected event handler to read:

@Override
public void onItemSelected(
 AdapterView<?> parent,
 View view,
 int position,
 long id) {
  TextView myTextView =
        (TextView) findViewById(R.id.textView);
  myTextView.setText(Integer.toString(position));
}

All that is happening is that the position parameter is displayed in the TextView. 

Finally to connect the eventhandling object to the Spinner we need to add it using its setOnItemSelectListener

spinner.setOnItemSelectedListener(onSpinner);

Putting all of this together gives the new onCreate:

@Override
protected void onCreate(
 Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 AdapterView.OnItemSelectedListener onSpinner =
      new AdapterView.OnItemSelectedListener() {

 @Override
 public void onItemSelected(
  AdapterView<?> parent,
  View view,
  int position,
  long id) {
   TextView myTextView =
     (TextView)findViewById(R.id.textView);
   myTextView.setText(Integer.toString(position));
 }

 @Override
 public void onNothingSelected(
  AdapterView<?> parent) {
 }
};

setContentView(R.layout.activity_main);
String[] country = {"Canada", "Mexico", "USA"};
ArrayAdapter<String> stringArrayAdapter=
                  new ArrayAdapter<String>(
 this,
 android.R.layout.simple_spinner_dropdown_item,country);
 Spinner spinner =
        (Spinner) findViewById(R.id.spinner);
 spinner.setAdapter(stringArrayAdapter);
 spinner.setOnItemSelectedListener(onSpinner);
}

If you now run the program you will see something like:

 

spinnerevent

The position displayed corresponds to the element in the array that has been selected - counting from zero of course. 

Most of the time is it enough just to have the index number of the selected item but the AdapterView object has a few methods that enable you to get the selected item. 

If you want to review the selected item you could use the position to index the original ArrayAdapter or even the original String array - but these aren't generally available to the event handler. So to retrive the item you would use the getItemAtPosition method.

For example to display the country name you would modify the setText call to: 

 myTextView.setText(
 (String) parent.getItemAtPosition(position));

Notice that the selected item is returned as an object type and you have to cast it before you can do anything with it. 

There are a range of other methods that can be used to retrieve information or manipulate the selected element but for most simple applications the getItemAtPosition is all you really need to know.

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 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 

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. 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. 



Last Updated ( Wednesday, 09 April 2014 )
 
 

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