Creating popup window android

Popupwindow is a floating view that is displayed on top of an activity. Android provides a PopupWindow class for creating a popup window with the custom design.

It is present from the first versions of the API, but not as popular as other dialog boxes due to the need for additional configuration, which is not always necessary.

Android PopupWindow very useful when you want to show the dialog just over the view items. For Example you can able to show the dialog near to the more option of your cardview / button view.

Check out my popup window android example demo.

Now we are going to create popup window showed in the popupwindow example video.

1. Adding Dependencies

In this example, we are going to show list of items in the recyclerview. So, we need recyclerview and cardview dependencies.

I have explained about using recyclerview and cardview in separate post. Please check it in the links.

2. Create PopupWindow Layouts

As mentioned in the design, First we need to create popupWindow layout with recyclerview.

Recyclerview need a adapter view to hold the popup items. So, we need to create adapter layout file.

3. Implement PopupWindow With Data

We are using recyclerview in the popup window. so, we need model class to hold the data.

Also, we need to create adpater to set popup items.

In the Adapter, set the click listener interface for the popup window click callbacks.

Already, we have created layouts and adapter for the PopupWindows. Lets create the PopupWindow.

In the above code, I am using adapter.setOnClick to pass the implementation of the RecyclerviewCallbacks interface to receive the callbacks of the popup window items.

4. Show / Hide the PopupWindow

Now, our popup window is ready to display. So, whenever we need to show the popup window. call the below code.

To dismiss the popup window,

That’s it. Now we can able to show and hide the popup window in android.

Download the example code from Github.

Thanks for reading.

Please try this with example and let me know your feedback in comments.

Источник

Tek Eye

The main screen for an Activity 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, get specific input, or show a brief message. Android has build in support for such small focused interactions that require immediate attention.

(This Android pop-up tutorial assumes that Android Studio is installed, a basic App can be created and run, and the code in this article can be correctly copied into Android Studio. The example can be changed to meet other requirements. When entering code in Studio add import statements when prompted by pressing Alt-Enter.)

How to Display A Smaller Window on Top of an Activity

There are different ways in Android to pop-up a brief window over the current Activity screen, these include:

  • 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 (see the article About Box in Android App Using AlertBuilder).
    • 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. For this article the PopupWindow class is used. This Android pop-up tutorial includes example code. What is the PopupWindow? The Android developer PopupWindow documention gives this class overview:

«This class represents 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 will be done in this tutorial. The steps for this example project and code are:

  • Create a new project in Android Studio.
  • Design the pop-up window.
  • Add the code to load and populate the pop-up window.
  • Call the code.

Design the Layout for the Pop-Up

For this example a pop-up is going to display a game’s result as gold, silver and bronze medal positions. The pop-up will have a graphic, shown in a 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 the Open Clip Art Library by user momoko. They have been resized for the Android project and are available in medals_png.zip. Ready to download and add into the app project.

Start a new app project in Android Studio. Here it was called Pop-up and uses an Empty Activity with all other settings left at their default values. The pop-up window will be defined in a new layout XML file in the project’s layout folder, called winners.xml. To add some interest to the pop-up screen it will have a blue background and rounded corners, this is done using a shape drawable (see Add a Border to an Android Layout). The shape drawable for the custom background definition is a drawable resource XML file in the folder res/drawable. With the app or res folder highlighted in the Project explorer use the File or context (often called right-click) menu. Select the New then Android resource file option. Call the new resource customborder.xml:

Add this code for the pop-up window background shape definition. The android:shape is a rectangle:

Add the images for the medals to the project’s res/drawable folders (see medals_png.zip). Now create the winners.xml layout file, again use the New menu and select XML then Layout XML File. A RelativeLayout is used for the Root Tag. Open the file, add the ImageViews for the medals and TextViews for winners names and scores. Here is the code used for the layout used in this example:

Code to Load a Pop-up Window

The code to display the pop-up window will be wrapped in a function called showWinners(). It can be called from a button press or other action. The first code in the function inflates the pop-up window layout using a LayoutInflater :

The inflated layout is used to get the id of the TextViews. The ids are used to set the names of the winners and their scores, e.g. here we assume that the name of the gold medal winner is stored in the string goldWinner:

The pop-up window is created by passing in the layout and required size. We defined a size in the XML which is used here, scaled by the screens density to support different devices:

The button on the pop-up is given an OnClickListener so that the pop-up can be closed (if not familiar with coding event handlers see the article Different Ways to Code Android Event Listeners).

A touch event outside of the pop-up will also close it. The trick here is to call setBackgroundDrawable with a transparent drawable. This allows for screen presses outside of the pop-up to also close the pop-up:

Finally display the pop-up:

Calling the Pop-up Function

The following listing is for a simple Activity with a button that has an OnCLickListener to call the showWinners() function that is described above. The names of the medal winners and there scores are simple variables, in a real app game they would come from the game results. This is the complete code for the example in action shown at the beginning of the article:

Читайте также:  Бизнес календарь для андроид

Bookmark this page in your browser so that you can use the code as a template for future projects that require a pop-up.

See Also

  • Download the project code for this pop-up example, available in android-pop-up.zip ready for importing into Android Studio
  • For more android example projects see the Android Example Projects page.
  • The medal images are also available via the Free Launcher Icons, Menu Icons and Android Graphics page.
  • View the Tek Eye full Index for other articles.

Author: Daniel S. Fowler Published: 2013-02-05 Updated: 2017-07-23

Do you have a question or comment about this article?

(Alternatively, use the email address at the bottom of the web page.)

↓markdown↓ CMS is fast and simple. Build websites quickly and publish easily. For beginner to expert.

Free Android Projects and Samples:

Источник

Apps often need to provide the user with a consistent experience for executing actions that are contextually specific. The most common actions for an activity live on the default Action Bar but actions that are more specific to an item or element can be displayed contextually using menus and popups. In addition to menus, apps often need to display popup overlays that contain informational content. This guide covers how to manage menus and popups within your Android apps.

In modern Android apps, there are a few mechanisms for displaying secondary content or actions related to an Activity:

  • Contextual Action Modes — An «action mode» which is enabled when a user selects an item. Upon the item selection, the actionbar switches to a contextual mode that presents relevant actions.
  • PopupMenu — A modal menu that is anchored to a particular view within an activity. The menu appears below that view when it is selected. Used to provide an overflow menu that allows for secondary actions on an item.
  • PopupWindow — A simple dialog box that gains focus when appearing on screen. It is used to display additional information on screen and is simpler but less flexible than a DialogFragment.
  • DialogFragment — A fully customizable dialog overlay that appears ontop of the activity and can contain arbitrary content as defined within the fragment. This is the most flexible but also the heaviest approach to displaying overlay content.

Let’s take a look at each one of these.

Contextual Action Modes can be enabled when a user selects or focuses on any item. Upon the item selection, the ActionBar switches to a contextual mode that presents relevant actions for said item.

Important actions related to the view item should be presented by constructing these contextual action modes whenever possible. The action mode is typically presented upon long click of a view or by selecting a checkbox within the activity.

Let’s take a look at how to create a contextual action mode for a view which will be presented when a view is long clicked. First, let’s define a menu XML file to be displayed in a res/menu/actions_textview.xml file:

Next, let’s define a ActionMode.Callback which will be manage the behavior of our contextual action menu:

Now that we have an ActionMode we can enable for any view (i.e TextView) or AdapterView (such as a ListView) which will display a contextual action bar for that element.

To activate the contextual action mode defined above for a simple TextView, we just need to attach the OnLongClickListener for the view and then trigger the action mode using startActionMode :

That’s all and now you have a TextView that upon long clicking will reveal the contextual action bar menu as show below:

We can also enable contextual menus for ListView items as well. This is as simple as setting the setOnItemLongClickListener property for the list items and then presenting the action mode. Given the same action mode defined the previous sections, we can apply the mode to items with:

Читайте также:  Poweramp для андроид крякнутый

This will trigger the contextual action menu whenever a list item is long-clicked. Notice that we also store the currentListItemIndex so we can act directly on the correct item after an action is selected. For example, the modeCallback might have a onActionItemClicked defined as:

This will result in the following after being defined correctly:

Using this approach we can easily allow users to act on items within a list. Note that in certain cases we may want to also support batch modes where more then one item can be affected by a contextual action. In that case, we need to use a MultiChoiceModeListener as the ActionMode as explained in the official menus docs.

A modal menu that is anchored to a particular view within an activity and the menu appears below that view when displayed. Used to provide an overflow menu that allows for secondary actions on an item.

Note that if the items change the selected content, consider using the «Contextual Action Mode» explained above. Instead, use this for actions that relate to the content, for example triggering a reply to a message.

Defining a PopupMenu for a view is as simple as constructing the PopupMenu object and then defining the menu XML that you would like to display. For example, if we wanted to present a popup menu for filtering items when a button was clicked, first we define the menu XML for that button in res/menu/popup_filters.xml :

Next, we define a click handler for the button that displays the PopupMenu :

With that setup, whenever the button is pressed, the menu will be displayed and a different action will be taken based on the item selected. Here’s the result:

In addition to contextual action modes and popup menus, there are also a more customizable PopupWindow concept. PopupWindow is a floating content container that appears over the current activity like a simplified DialogFragment that is less flexible but easier to implement. Popups are usually used to show some additional information or something user wants to know after an event takes place.

To display a PopupWindow , let’s first download a background to use for the popup within res/drawable/popup_bg.9.png . The background is a nine-patch image which will be used as the background for the popup content.

Next, let’s define an arbitrary XML layout file which will be displayed within the popup at res/layout/popup_content.xml :

Now, we have the background and the content layout defined so we can setup the popup to display when a button is clicked with:

Finally, we need to define the displayPopupWindow method to actually construct and display the window based on our content area and background image:

The result of this is a dismissable popup window with our content and which looks like:

Read more details on the PopupWindow tutorial. You might also want to check out this extended DismissablePopupWindow for a simple re-usable popup that had a dismiss button embedded within the window.

Prior to Android 3.0, there were several other relevent menu strategies which are now discouraged. The strategies that have been deprecated in modern apps are listed below:

  • Options Menu — This was a menu that appeared when a hardware «menu button» was pressed. This menu button has been deprecated and should no longer be used in modern apps. You can read more in the Creating an Options Menu official guide.
  • Floating Context Menu — This was a contextual menu that appeared to float above the activity with a list of menu items to select. This approach is deprecated in favor of the aforementioned Contextual Action Mode in modern apps. See this tutorial for another look at the deprecated floating context approach.

In certain cases, we may want to group menu items together within a menu XML. To group menu items simply wrap them in a group node in the menu xml:

Check out more details in the Menu Groups official docs which shows you how to create «checkable» items as well.

Источник

Оцените статью