Question

I have a view class that draws different colored circles onto the canvas.

I want to display a popup window near the circle when the circle is clicked to display the color of the circle. Right now I am facing problem trying to create the popup window.

Most of the tutorials does the popup window on activity class thus i could not find a example to reference to.

My code:

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
                    x = event.getX();
            y = event.getY();

                   // Open popup window
                       for(int i =0; i < circles.size(); i++){
            if (buttonClick == true && circles.get(i).contains(x, y)) {

                                   View view = inflate(getContext(),R.layout.popup_layout, null); 
                PopupWindow popup = new PopupWindow(view);
    popup.showAtLocation(MainActivity.returnView(), Gravity.LEFT, (int)x, (int)y);

                        }
                           } 
             break;
}

Popup window xml file

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:background="@android:color/background_light">
 <LinearLayout 
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:orientation="vertical" 
     android:layout_margin="1dp"
     android:background="@android:color/WHITE">
     >
     <LinearLayout 
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:orientation="vertical" 
      android:layout_margin="20dp">
      <TextView
           android:id="@+id/ColorTV"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Insert Text here" />
      <Button
          android:id="@+id/dismissbtn"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Dismiss" />
      </LinearLayout>
 </LinearLayout>
</LinearLayout>
Was it helpful?

Solution

You can use PopupWindow. Use PopupWindow#showAtLocation (View parent, int gravity, int x, int y) method to put your popup where you want it, using your view itself as the parent.

So, inside your View's onTouchEvent, you could have:

View view = inflate(R.layout.my_popup_view, null); // however you'll inflate your view
PopupWindow popup = new PopupWindow(view, 300, 300, true);
popup.showAtLocation(this, Gravity.LEFT, x, y);

or something similar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top