This application illustrates how to use multiple Activities in a single application and pass data from one Activity to another. The ImageViewer Activity displays an image using an ImageView and contains a Button for launching the ImageChooser Activity, which is used to select which image to display.
To see how this works download the source code here.
First open the ImageViewer.java file located in the src/ directory in the edu.calpoly.android package
The onCreate method instantiates the layout and member variables for the Views
Notice how the OnClickListener is set for the Button, an anonymous inner type is used which allows the Button to be given functionality without needing to have a class that implements OnClickListener
The click listener for the Button creates an Intent that is used to start the ImageChooser Activity. The startActivityForResult method is used to indicate that when the ImageChooser Activity finishes it should return a value to be used by ImageViewer
The protected void onActivityResult(int requestCode, int resultCode, Intent data) method is called when the ImageChooser Activity finishes
First we ensure that the requestCode parameter matches the unique request code for starting an ImageChooser Activity
Next the resultCode is checked to ensure that ImageChooser completed successfully
Finally we extract a String representing the image choice from the data parameter and display the appropriate image
Now open the ImageChooser.java file
This Activity contains two Buttons, one for selecting a Cal Poly logo to display and one for selecting an Android icon
The Activity implements OnClickListener by containing the onClick method, notice that both Buttons share the same OnClickListener
In the onClick method we first determine which Button was pressed by checking the View parameter
An Intent is created to pass the selection back to the ImageViewer Activity, the selection is indicated by a string value corresponding to either Cal Poly or Android and added to the Intent using a string as a key. This key is used by ImageViewer to retrieve the selection
If an image was chose successfully the result is set and the Activity finishes
To modify this application you will be adding a Toast notification when an image is selected
A Toast is a small window that displays text that appears on the screen for a short period of time.
You will be adding the code to display the Toast inside of the onClick method in ImageChooser.java
To
create a new Toast use the static method:
Toast.makeText(Context
context, CharSequence text, int duration)
Obtain the Context using getApplicationContext()
text should be either the string “Cal Poly selected” or “Android selected”
For the duration use the static field Toast.LENGTH_SHORT
Now to display the Toast use the method Toast.show()
When finished you should be able to run the application and see something like this: