The android.widget.PopupWindow class is another class that provides a popup window function besides AlertDialog. There is something different between them. This example will show you how to use the android.widget.PopupWindow in the android application.
1. PopupWindow And AlertDialog Difference.
- The main difference between AlertDialog and PopupWindow is the location of the display. The AlertDialog is fixed display on the screen, while PopupWindow can be displayed anywhere on the main screen.
- PopupWindow is a pop-up control that can be used to display any View and float at the top of the activity.
- Through PopupWindow we can achieve a variety of pop-up window effects such as information display or UI interaction.
- The PopupWindow custom layout is more convenient, and the display position is freedom there is no restriction.
2. PopupWindow Methods.
2.1 PopupWindow Constructor Method.
- public PopupWindow (Context context).
- public PopupWindow(View contentView) .
- public PopupWindow(View contentView, int width, int height) .
- public PopupWindow(View contentView, int width, int height, boolean focusable)
- Please Note: There are four constructors, but the basic three parameters for generating a PopupWindow must be set are: View contentView, int width, int height; You can’t pop a PopupWindow without any one of them!
- So, if you use the first constructor, the complete construct code should look like this.
View popupContentView = LayoutInflater.from(ActivityClass.this).inflate(R.layout.popup_view_Layout, null); PopupWindwo popupWindow = PopupWindow(context); popupWindow.setContentView(popupContentView); popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
2.2 PopupWindow Display Methods.
- showAsDropDown(View anchorView): Show popup at the position of the relative control (lower left), no deviation.
- showAsDropDown(View anchorView, int xOffSet, int yOffSet): Show popup at the position of the relative control. xOffSet represents the offset of the x-axis, positive to the left, negative to the right. yOffSet represents the offset of the y-axis, positive to the down, negative to the up.
- showAtLocation(View parentView, int gravity, int xOffSet, int yOffSet): Show popup at the location specified by the gravity value. ( Gravity.CENTER, Gravity.BOTTOM) etc.
2.3 PopupWindow Other Methods.
- public void dismiss(): Close popup window when needed.
- public void setFocusable(boolean focusable): Let PopupWindow get the focus, then it will be able to handle the click event of the physical button, otherwise the event will be passed up by the Activity. If there is an Editor in PopupWindow, the focusable value must be true.
2.4 Add Animation To PopupWindow.
- PopupWindow.setAnimationStyle(R.style.ContextMenuAnim) can be used to add animation to a popup window.
popupWindow.setAnimationStyle(R.style.popup_window_animation_phone);
- The above popup_window_animation_phone is a style defined in app / res / values / styles.xml file.
<style name="popup_window_animation_phone"> <item name="android:windowEnterAnimation">@android:anim/fade_in_animation</item> </style>
- The fade_in_animation and fade_out_animation are also custom-defined animation XML file saved under app / res / animator folder.
- fade_in_animation.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:duration="1500" android:fromAlpha="0.1" android:toAlpha="1" /> </set>
- Below are the create animation XML file steps.
- Right-click the app/res folder.
- Click New —> Android resource file menu item in the popup menu list.
- Input the File name and choose Animator in the Resource type drop-down list.
3. Android PopupWindow Example.
You can see this example demo video at the end of this article page.
3.1 Main Layout XML File.
- This layout file defines the above “Short Message” and “Phone Call” buttons.
- activity_popup_window.xml
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/smsButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Short Message" /> <Button android:id="@+id/phoneButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Phone Call" /> </LinearLayout>
3.2 Short Message Popup Window Layout Xml File.
- This XML file defines a ListView object which will be displayed in the short message popup window.
- It also defines a LinearLayout object which will be used to display the list item row. Each list item row has an ImageView and a TextView.
- activity_popup_window_sms.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/popupWindowSmsList" android:layout_width="match_parent" android:layout_height="match_parent" /> <LinearLayout android:id="@+id/smsListItemRow" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/smsListItemImage" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_alignParentBottom="true"/> <TextView android:id="@+id/smsListItemText" android:layout_width="wrap_content" android:layout_height="match_parent" android:textSize="20dp" android:textStyle="bold" android:layout_alignParentTop="true" android:layout_alignParentBottom="true" android:layout_toRightOf="@id/smsListItemImage"/> </LinearLayout> </LinearLayout>
3.3 Phone Call Popup Window Layout Xml File.
- This XML file defines a ListView object which will be displayed in the phone call popup window.
- activity_popup_window_phone.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/popupWindowPhoneList" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
3.4 Main Activity Java File.
- PopupWindowActivity.java
package com.dev2qa.example; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.SimpleAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PopupWindowActivity extends AppCompatActivity { // Save short message command text in item list. private String smsCmdArr[] = {"New", "Delete", "Settings", "BookMark", "Block"}; // Save short message command item image. private int smsCmdImgArr[] = {R.drawable.message_new, R.drawable.message_delete, R.drawable.message_settings, R.drawable.message_bookmark, R.drawable.message_block}; // SimpleAdapter list item key. final private String LIST_ITEM_KEY_IMAGE = "image"; final private String LIST_ITEM_KEY_TEXT = "text"; // Save phone command text. private String phoneCmdArr[] = {"Dial", "Contacts", "Audio Record"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_popup_window); setTitle("dev2qa.com --- Popup Window"); this.createSmsPopup(); this.createPhonePopup(); } // Create short message popup window. private void createSmsPopup() { // Get short message button. final Button smsButton = (Button)findViewById(R.id.smsButton); smsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Initialize short message list item data. List<Map<String, Object>> itemList = new ArrayList<Map<String, Object>>(); int itemLen = smsCmdArr.length; for(int i=0;i<itemLen;i++) { Map<String,Object> itemMap = new HashMap<String, Object>(); itemMap.put(LIST_ITEM_KEY_IMAGE, smsCmdImgArr[i]); itemMap.put(LIST_ITEM_KEY_TEXT, smsCmdArr[i]); itemList.add(itemMap); } // Create SimpleAdapter that will be used by short message list view. SimpleAdapter simpleAdapter = new SimpleAdapter(PopupWindowActivity.this, itemList, R.layout.activity_popup_window_sms, new String[]{LIST_ITEM_KEY_IMAGE, LIST_ITEM_KEY_TEXT}, new int[]{R.id.smsListItemImage, R.id.smsListItemText}); // Get short message popup view. View popupView = getLayoutInflater().inflate(R.layout.activity_popup_window_sms, null); ListView smsListView = (ListView) popupView.findViewById(R.id.popupWindowSmsList); smsListView.setAdapter(simpleAdapter); smsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int itemIndex, long l) { AlertDialog alertDialog = new AlertDialog.Builder(PopupWindowActivity.this).create(); alertDialog.setTitle("Short Message Function"); alertDialog.setMessage("You select command " + smsCmdArr[itemIndex]); alertDialog.show(); } }); // Create popup window. PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); // Set popup window animation style. popupWindow.setAnimationStyle(R.style.popup_window_animation_sms); popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE)); popupWindow.setFocusable(true); popupWindow.setOutsideTouchable(true); popupWindow.update(); // Show popup window offset 1,1 to smsBtton. popupWindow.showAsDropDown(smsButton, 1, 1); } }); } // Create phone popup window. private void createPhonePopup() { // Get phone button. final Button phoneButton = (Button)findViewById(R.id.phoneButton); phoneButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Get phone popup view. View popupView = getLayoutInflater().inflate(R.layout.activity_popup_window_phone, null); // Get phone list view. ListView phoneListView = (ListView) popupView.findViewById(R.id.popupWindowPhoneList); // Set header text in list view. TextView headerTextView = new TextView(PopupWindowActivity.this); headerTextView.setText("Phone Popup Window"); headerTextView.setTextSize(15); headerTextView.setBackgroundColor(Color.GREEN); phoneListView.addHeaderView(headerTextView); // Create phone data adapter. ArrayAdapter<String> phoneCmdAdapter = new ArrayAdapter<String>(PopupWindowActivity.this, android.R.layout.simple_list_item_1, phoneCmdArr); phoneListView.setAdapter(phoneCmdAdapter); phoneListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int itemIndex, long l) { AlertDialog alertDialog = new AlertDialog.Builder(PopupWindowActivity.this).create(); alertDialog.setTitle("Phone Function"); alertDialog.setMessage("You select command " + phoneCmdArr[itemIndex]); alertDialog.show(); } }); // Create popup window. PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); // Set popup window animation style. popupWindow.setAnimationStyle(R.style.popup_window_animation_phone); popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE)); popupWindow.setFocusable(true); popupWindow.setOutsideTouchable(true); popupWindow.update(); // Show popup window offset 1,1 to phoneBtton at the screen center. popupWindow.showAtLocation(phoneButton, Gravity.CENTER, 0, 0); } }); } }
3.5 PopupWindow Animation Style Xml File.
- app / res / values / styles.xml
<style name="popup_window_animation_sms"> <item name="android:windowEnterAnimation">@android:anim/slide_in_left</item> <item name="android:windowExitAnimation">@android:anim/slide_out_right</item> </style> <style name="popup_window_animation_phone"> <item name="android:windowEnterAnimation">@android:anim/fade_in</item> <item name="android:windowExitAnimation">@android:anim/fade_out</item> </style>
3.6 PopupWindow Custom Defined Animation XML File.
- Below two animator files are saved in app/res/animator folder. They are used by styles in 3.5.
- fade_in.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:duration="1500" android:fromAlpha="0.1" android:toAlpha="1" /> </set>
- fade_out.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:duration="1500" android:fromAlpha="1" android:toAlpha="0.1" /> </set>
4. Example Demo Video.
- You can click the URL android popup window animation example to see this example demo video.