How to Display A Smaller Window on Top of an Activity
The Activity screen is not the only way to interact with the user of an App. A brief message or dialog can be displayed in appropriate circumstances to ask a specific question or get specific input. Android has build in support for such small focused interactions that require immediate attention.
- The Toast class – to display brief informational only message.
- The Dialog class, managed by a DialogFragment – to support a flexible input that can display information and can ask for inputs or choices. There are several built in sub-classes including:
- AlertDialog – supports buttons (from zero to three), list selections, check boxes and radio buttons.
- ProgressDialog – supports a progress bar or wheel and supports buttons because it extends AlertDialog.
- DatePickerDialog – supports selecting a date.
- TimePickerDialog – supports a time selection.
- The PopupWindow class – allows a View to float on top of an existing activity. Suitable for custom informational messages.
These classes build their user interfaces through class methods with support from custom layouts when required. This article looks at using the PopupWindow class. What is the PopupWindow? The Android developer documention has the following class overview:
“A popup window that can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current activity.”
It can be used to display extra information without needing to code another Activity. An example would be to show results at the end of a game (or end of a level), which we will be doing in the following tutorial. The steps for this example code are:
- Create a new project.
- Design the pop-up window.
- Add the code to load and populate the pop-up window.
- Call the code.
Open a Project to Add the Pop-Up Window
In this tutorial we are assuming that you have a working project in Eclipse to use as a base, either open an existing project or create a new one (if you need help see Your First Android Hello World Java Program).
Design the Layout for the Pop-Up
For this example we are going to have a pop-up to display a game’s result as gold, silver and bronze medal positions. The pop-up will have a graphic (ImageView) for each of the medals, a TextView for the winner’s name and one for the score. The images for the medals came from Open Clip Art Library user momoko. They have been resized for an Android project and you can download medals_png.zip ready for importing into a project.