views:

4252

answers:

3

I looked online and was not able to find a working example of the PopupWindow class. The code examples I found online either compile but do not work, or are using methods which have since been removed (such as Activity.getViewInflate()).

Is there a simple working example that displays a PopupWindow?

+7  A: 

I created a working example based on this Google Groups post.

To create a simple working PopupWindow, you'll need to do the following:

  1. Create a layout XML which describes the View that will be rendered within the PopupWindow.
  2. Invoke the PopupWindow by inflating the layout XML, and assign the appropriate "parent view" to the pop-up.

popup_example.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="Test Pop-Up"
    />

</LinearLayout>

Java code:

    LayoutInflater inflater = (LayoutInflater)
       this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    PopupWindow pw = new PopupWindow(
       inflater.inflate(R.layout.popup_example, null, false), 
       100, 
       100, 
       true);
    // The code below assumes that the root container has an id called 'main'
    pw.showAtLocation(this.findViewById(R.id.main), Gravity.CENTER, 0, 0); 
Todd
A: 

main.xml
android:layout_width="fill_parent" android:layout_height="wrap_content"

android:text="@string/hello"

/>
   <ImageButton android:id="@+id/btnFindMe"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content" 
   android:layout_centerInParent="true"
    android:background="@drawable/qqw"


   >

    </ImageButton> 

pw.showAtLocation(this.findViewById(R.id.l1), Gravity.CENTER, 0, 0);
setContentView(R.layout.main); I used your code but appear work bad.can you tell me my mistake

pengwang
A: 

the code is assuming that you are within an activity. But, for example if we want to create something just like the alarm, from where should we take the context, the findViewById() and all things related to a running activity?

I want to use popup windows just like that, no matter which activity is running. In fact, the popup window caller doesn't extends Activity.

Ideas?

Sebastian
in other words, how we get the parent View when it can be a View from any activity running on foreground.
Sebastian
I'd suggest opening a new question here about your problem.
Todd
i'd suggest you read again...
Sebastian