Search code examples
androidandroid-popupwindow

PopupWindow not showing


I have founded many solutions for this problem but none of them have worked for me. I want to show a PopupWindow inside a Fragment. This is my code

LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View popupView = layoutInflater.inflate(R.layout.pop_up_cargando, null,false);
this.popupWindow = new PopupWindow(popupView, popupView.getWidth(),popupView.getHeight());
this.popupWindow.setFocusable(true);
int location[] = new int[2];
this.btnInventario.getLocationOnScreen(location);
this.popupWindow.showAtLocation(this.btnInventario, Gravity.NO_GRAVITY, location[0], location[1] + btnInventario.getHeight()); // this.btnInventario is the button that calls this code
this.popupWindow.update(0, 0, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

But the PopupWindow never appears.

Edit: This is the content of pop_up_cargando

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/popup_recomendar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:orientation="vertical" >
    <ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"
        android:id="@+id/cargando"/>
    <TextView
        android:id="@+id/txtTexto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_gravity="center"
        android:text="@string/vacio"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>

Any suggestions? What I'm doing wrong? Your help will be very appreciated.


Solution

  • Your popupView.getWidth() and popupView.getHeight() values are equals to 0 because the view has not been drawn yet.

    Before asking for the width and the height of your view, you have to ensure that it has been drawn. For that you can call the following method after it has been inflated:

    popupView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    

    After that, the size of your view is available with the methods getMeasuredWidth() and getMeasuredHeight().