Upward Mobility: Android for iOS Developers, Part 3

Handling Input Events

Now that our Android app lets you choose what planet you’re on, we should use that information to update our “Hello, world” message based on the selection. To do that, we’re going to need to handle the selection event on the spinner we created.

To do this, we need to set the setOnItemSelectedListener property on our spinner to something that implements the OnItemSelectedListener interface. The simplest way to do this is to implement it in our activity.

This is pretty straight-forward stuff. You use the parent.getItemAtPosition call (where parent is the spinner) to get the item that you selected. The item is just the string value of the selection, so we can use a simple string compare to select the appropriate message. In the same way that we got the spinner using it’s id, we can get a handle on the text view at the top of the screen, and then set the message using setText.

There are a couple of things to point out here, however. For one, the onItemSelected message gets called when the widget is created, a fact that irritates the heck out of Android developers. This means that you need to ignore the first call to the method. Thus, the purpose of the spinnerActive flag. Secondly, because we’re using the Activity as the listener, you could end up with problems if you have multiple spinners on the screen, since they would all call the same listener. You could either use the AdapterView value to determine which spinner fired the event, or use private inner classes to handle the various spinners.

Now that we’ve got our listeners implements, the last step is to tell the spinner to use the Activity as the handler.

Now when we fire up the app and select a value from the spinner, we get a personalized welcome message!

Screen Shot 2013-06-21 at 6.13.45 AM

tags: , ,